Cocoa and the Builder Pattern

By uliwitness

There’s been a nice discussion about the Builder pattern on Twitter today. The Builder pattern is a nice tool to have, particularly because it addresses a few common problems.

What Builder Pattern?

In short, the Builder pattern is a pattern where you have one object that you configure that then creates another object based on that configuration. The nice thing here is that you can first build your object step by step, like you’d e.g. do with NSMutableString, but then the actual construction of the object happens in one go. Very handy for immutable objects.

Usually, a setter for a Builder object returns self, like retain or autorelease do. That way, you can create something in Java or C++ that almost looks like Objective C:

Image theImage = (new Image.Builder)->SetWidth(100)->SetHeight(80)->SetDepth(8)->Build();

Where the Build() method releases the builder and returns the actual, immutable Image object.

Extending init methods

When you add a parameter to an initializer in Objective-C, it is annoying. You usually add the parameter to the initializer, then create a compatibility version with the old method’s name that calls the newer version with a default value for the extra parameter.

Java and C++ have solved that problem by allowing you to specify default values for parameters, but they don’t maintain binary stability that way. If you add a parameter, you still have to recompile, but at least you don’t need to change your code.

I guess one fix would be if ObjC supported default arguments to a parameter that would simply result in the creation of a second version of this initializer with the label and parameter removed:

-(id) initWithBanana: (NSBanana*)theBanana curvature: (CGFloat)curvature = 5
    // magic happens here

Would be the same as writing:

-(id) initWithBanana: (NSBanana*)theBanana curvature: (CGFloat)curvature
    // magic happens here

-(id) initWithBanana: (NSBanana*)theBanana
    return [self initWithBanana: theBanana curvature: 5];

Of course, you’d still need at least one parameter, because ObjC has no way of knowing what part of the message is the name, and what is the label for the second (for init there could be special code, I guess, but what for a -exfoliateCow:withSpeed: method?). And defaulting to -initWithBanana if the first parameter has a default is obviously not always desirable either. It would solve the annoyance of telescoping constructors, at the least.

The Builder pattern doesn’t have this problem. Each parameter has a setter that you use to set it. A new builder could have defaults for all parameters when it is created. Then you change the ones you want to customize, and call -build on it to get the new object. If a new setter is added, that’s fine. You don’t call it, you get the default. The maintainers only add the one setter, no compatibility method needed.

Thread safety and immutable objects

The easiest way to get thread safety is to prohibit data from changing. If data is immutable, there is nothing to be synchronized between threads,and no need for one thread to wait for the other. However, immutable objects are also annoying, as they need to be fully specified in their init method.

A case where this is a problem in Cocoa is NSImage. NSImage is an immutable object by convention, but not actually. It is an object that has its own builder built in. You are expected to know that, for an NSImage to be thread safe, you are expected to create it, set its attributes, draw something in it, and then stop messing with it, treating it as an immutable, read-only object from then on.

The problem is, nobody enforces it. NSImage is a perfectly mutable object, with setters and getters. There is no exception thrown when you violate this verbal contract. Of course Apple could have added a “makeImmutable” method to NSImage that causes those exceptions to happen when you try to edit an instance. But then they’d have to add code to each setter that errors (Or at the least use some aspect-oriented-programming mechanism to inject code before every setter that performs this check automatically).

The Builder pattern would solve that: They can have a huge, private constructor on NSImage that changes with every release to add new parameters and initialize that immutable object, while the Builder would present a stable and convenient API to all clients. There would not be any setters on NSImage.

But it is ugly…

Admittedly, it feels a bit inelegant to build an object that builds an object. The way NSImage works is so much nicer. But Mike Lee actually offers a neat approach that works almost as well:

Just pass in a list of properties. This could be a dictionary of properties, or even just a variadic argument list like -dictionaryWithObjectsAndKeys: takes it. You’d define a constant for each possible property (that way if you mis-type the parameter name the compiler tells you, which you don’t get from a raw string). Internally, this constant could even hold the actual name of the property, even if it is never exposed as a method in the public header. So, all your constructor would do is call [self setValue: properties[key] forKey: key] in a loop, once for every element.

You get the same effect as labeled parameters (if you put the keys first, even more so). You also get the same effect as optional parameters. The binary ABI never changes, so that’s good, too. The only downside is you need to pass every parameter as an object, and you lose compile-time type checks. OTOH you gain compile-time errors when you try to change the object after creating it (because it declares no setters).

Is it worth all that work?

Admittedly, I haven’t had to add parameters to the init method of a public class that often. Nonetheless, I think Mike’s approach and the Builder pattern both are useful things to keep in mind if you ever come up with a class that can be created in numerous configurations (and is likely to gain new properties in the future) but should then be immutable. Class clusters and plug-in classes seem like a typical place where you might need this.

Share your thoughts