D.NET Source Released
Cristi Vlasceanu has released the source to the D.NET compiler backend under the Microsoft Public License, with the qualifier that the code "is not of production quality" and "is intended for research and educational purposes."
Self-Configuration of Classes With Delegates
Sometimes you need to execute different code paths depending upon certain runtime parameters. For example, in graphics applications it is quite common to create different rendering paths based upon the graphics API features supported by the user's graphics card. In simple cases, this can be handled with an if...else block, or perhaps a switch. More complex cases need more. In C, you might set function pointers during app startup. In C++ or Java, you might use different implementations of an interface or of an abstract class. In D, you can do many of the same things as other languages. You can also put all of your variable code paths in one class, rather than subclasses or different interface implementations, and let instances configure themselves in the constructor using delegates.
Here's a simple example that configures an instance of a class based upon the value of a static counter:
// selfdelegate.d
import std.stdio;class Printer
{
public:
this()
{
if(count++ == 0)
print = ¬hingPrinter;
else
print = &somethingPrinter;
}
void delegate() print; // delegate configured during instantiation
private:
void nothingPrinter()
{
writefln("Nothing.");
}
void somethingPrinter()
{
writefln("Something");
}
static int count = 0;
}void main()
{
Printer p1 = new Printer;
Printer p2 = new Printer;
p1.print();
p2.print();
}
Here's a sample execution:
C:\projects\D\tests>dmd -run selfdelegate
Nothing.
Something
If you have many methods that need to be configured, you may prefer to use a factory and instantiate different implementations of an interface. That approach limits you to some extent, however.
For example, consider an OpenGL renderer interface that has three implementations: an advanced version, an intermediate version requiring at least version 1.x of OpenGL, and a legacy version for OpenGL 1.1. What if the user's graphics card doesn't support a few of the extensions used by the advanced version, but does support most of them? With the set up described, you'd have no choice but to fall back to the intermediate or legacy version. Wouldn't it be better if you could make use of the advanced features that are supported and use fallbacks only for those that aren't? There are several different ways to mix and match like that. Using delegates for a class to configure itself at runtime is one you might not have thought of.
Technorati Tags: D Programming Language, delegates
Singletons In D
The intent of the Singleton pattern is described by the Gang of Four thusly:
Ensure a class only has one instance, and provide a global point of access to it.
Singletons are ubiquitous in object oriented programming. They are also, I feel, abused and overused. But, I'm not going to go into a philosophical rant on how I think the pattern should and shouldn't be used. My goal today is just to show a few simple ways to implement the Singleton pattern in D.
First, we'll start with an implementation based on the first technique described by the GoF:
class MySingleton
{
public:
static MySingleton instance()
{
if(_instance is null) _instance = new MySingleton;
return _instance;
}private:
this() {}static MySingleton _instance;
}
This implementation instantiates the single object instance the first time the instance method is called. There are a couple of key points to note here that apply to all Singletons.
First, there is only one constructor and it is private. Exposing any constructors would defeat the purpose of having a Singleton by allowing users to instantiate instances of the object themselves. Simply omitting a constructor will not work either, since D automatically creates a public default constructor when none is declared. So all Singleton implementations should declare a private constructor. In most languages, this ensures that only the class can instantiate itself. In D, however, private class members are private to the module in which the class is declared and not to the class itself. As a rule of thumb, it's probably a good idea to define Singletons in their own modules when using the implementation above. If you do mix them with other code, be sure not to instantiate the Singleton more than once. You can protect yourself against this, though (see below).
The second point of note is that the single class instance and its accessor method are both static. This combined with the private constructor ensures that the class has complete control over the instantiation of the single instance (with the caveat about module scope mentioned above).
In Java, singleton instances are sometimes declared public rather than private, like this:
class JavaSingleton {
public static final instance = new JavaSingleton();private JavaSingleton() {}
}
The final keyword ensures that the instance is only instantiated once. Attempts to instantiate it again will result in compilation errors. D includes a final attribute as well, but it is not same as Java's. In Java, final can be applied to a class declaration to prevent subclassing, or to a member variable declaration to ensure it is only initialized once, or to a method to prevent it from being overridden by a subclass. In D, as far as I can tell, it only can be applied to methods to prevent them from being overridden by subclasses -- final classes can be subclassed (declaring a class final in D just means that none of its methods can be overridden) and final members can be reinitialized. So if you are tempted to use the same technique in D, you can't use the final keyword to do so. You'll have to use const instead.
If you declare the static object instance to be const, you must use a static class constructor to initialize it:
class MySingleton2
{
public:
static const MySingleton2 instance;private:
this() {}static this() { instance = new MySingleton2; }
}
It is possible to initialize static class members at the point of declaration, but the initialization value must be a constant (i.e. static int x = 10;). The new statement is not a constant value and therefore must be implemented in a static class constructor.
Static constructors are run by D during application initialization (though the D bootstrap code must be called manually when using a WinMain method on the Windows platform). Because the single object instance is initialized in a static class constructor, it is guaranteed to be initialized before the instance method is called. Furthermore, because the instance member is static const it can only be initialized in a static class constructor. Any attempt to initialize it outside of the static class constructor will result in a compiler error. You could make the instance member private and give it an accessor method, but there's really no reason to do so as long as it is static const -- the value of instance cannot be changed after it is initialized. If you make it private and remove the const, it will be vulnerable at module scope as mentioned above.
In D, I would suggest that you prefer this technique unless there is a reason to use lazy instantiation, in which case you should go with the first. Additionally, both implementations can be templated.
A template version of the first implementation:
class Singleton(T)
{
public:
static T instance()
{
if(_instance is null) _instance = new T;
return _instance;
}private:
this() {}static T _instance;
}class TMySingleton : Singleton!(TMySingleton)
{
}
And of the second:
class Singleton2(T)
{
public:
static const T instance;private:
this() {}static this() { instance = new T; }
}class TMySingleton2 : Singleton!(TMySingleton2)
{
}
These are 4 basic D Singleton implementations that should cover 99% of the use cases you will have for the pattern. When and how you use them and which version(s) you use I leave entirely up to you. What these implementations do not provide is a way to replace the single object instance with that of a subclass at initialization. Maybe I'll look at that another day (meaning, I haven't even attempted to implement it yet).
I've provided a source module which gives a simple example of using each of the above implementations. Compile it if you want, but you can just run it as a script:
dmd -run singleton.d
If you are using GDC, replace dmd with gdmd.
Technorati Tags: D Programming Language, Singletons, Gang of Four, Design Patterns, templates, programming
Some Useful Templates
Erik Rasmussen has posted a collection of D templates on his blog. You can use them to, as he says, "avoid the deadly programming sin of code duplication." Thanks, Erik!
Technorati Tags: D Programming Language, templates
Policy-based Free List
One of the reasons I was experimenting with policies earlier (1, 2) was to implement a policy-based free list I had seen in Game Programming Gems 5 in an article by Nathan Mefford of Firaxis (1.11 Improving Freelists with Policy Based Design). I'm fairly satisfied with the implementation I put together.
The implementation uses two policies as suggested in the article, one to determine how the free list should grow (the Growth Policy) and another to determine how it objects should be stored, allocated, and managed (the Allocation Policy). By default, I added two Growth policies and two Allocation policies to the freelist module. The allocation policies both store objects in a dynamic array and grow the array by manipulating its length property. The only difference between the two is how they handle object that are returned to the free list when it is full.
The two Growth policies can be combined with the two Allocation policies to cover most of the situations I could think of that I would most commonly want. I thought of several corner cases, but I didn't implement default policies for those. If I need them later I can implement them separately on a case-by-case basis.
The module is part of a D game engine I am working on (who isn't these days?), but having seen some talk about free lists over in the DSource forums I decided to release it here. While I will ultimately release the full engine under a BSD License, I am releasing the free list implementation in it's current state into public domain. If you use it, be sure to add a module statement to the file to fit your project. For this release, I declared "module freelist;". That leaves a potential for name collisions, so you should put it in your own package heirarchy. Change the name, change the implementation, do whatever you want with it. It's public domain. Also, it hasn't been fully tested. I tested an earlier version exhaustively, but made some heavy changes to it since. If you find any bugs in the documenation or the source, let me know if you want. I'm not supporting this release in any way, but bug fixes will help the version I evolve as part of my engine project.
Download freelist.d. I hope you find it useful.