Ayende @ Rahien

It's a girl

Design patterns in the test of time: Mediator

The mediator pattern defines an object that encapsulates how a set of objects interact. This pattern is considered to be a behavioral pattern due to the way it can alter the program's running behavior.

More about this pattern can be found here.

Like the Façade pattern, I can absolutely see the logic of wanting to use a mediator. It is supposed to make it easier to work with a set of objects, because it hides their interactions.

In practice, almost all known cases are bad ones. In fact, in most systems that I have seen any association of the name to the actual pattern it is supposed to represent is not very associated at all.

The differences between façade and mediator are minute, and you would think the same advice would apply. However, while you can find a lot of usages of facades (or at least things people would call facades), there are very few real world examples of mediator pattern in use. And almost all of them carry the marks that say: “Just read GoF book, @w$0m3!!!”

Design patterns in the test of time: Iterator

In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.

More about this pattern.

It is really hard to think about any other pattern that has been more successful. In particular, patterns have long been about overcoming shortcoming of the language or platform.

In this case, iterators has became part of both language and platform in most modern systems.

  • System.Collection.IEnumerable
  • java.util.Iterator
  • Python’s __iter__()

Basically, it is so good, it is everywhere.

Design patterns in the test of time: Interpreter

In computer programming, the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol (terminal or nonterminal) in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence.

More about this pattern.

Along with the visitor pattern, this is still a very useful pattern, but in a very small but important context. Parsing and executing code. We see those quite often. In particular, JavaScript is probably the most common place where we see interpreters.

That said, unless you are actually dealing with executing code, there is very little reason for you to want to apply this pattern. In fact, I have seem people go for that several times for purposes that I really can’t explain.

Interpreter is for code execution. It has some interesting differences from compiling the code. For one, it is a lot easier to write, and for the most part, performance is great. This is especially true because the hard parts (the text parsing) are usually done up front and then you are just executing the AST.

From my perspective, we use Jint, a JS interpreter in RavenDB because compiling to IL and running that was complex. Any bugs there was complex to figure out, and most important from our point of view, we really needed to be able to place limits on what you could do. The number of steps that can be taken, the recursion depth, and so on. Doing so with compiled code requires you to have kernel level access, or doing things like Thread Abort.

So Interpreters are good, but watch out when you use it, if it ain’t code that you are going to run, why are you writing this in the first place?

Design patterns in the test of time: Command, Redux

In my previous post about the command pattern, I gushed about how much I loved it. That doesn’t mean that the command pattern as originally envisioned is still completely in fashion.

In particular, the notion of “Undo” was  one of the major features in the command pattern’s cap. Today, that is almost never the case. Sure, if you are building an application such as an editor. Something like Photoshop or a text editor would find the notion of commands with the ability to have an undo stack very compelling. Other than that, however, that is a very rare need.

In most business scenarios, there really is no good way to undo things. How would you implement SendEmailCommand.Undo(), for example? But even something like PlaceOrder.Undo() is a lot more complex and hard to do than you would think. The mere notion of undoing the operation assumes that this isn’t going to have any side affects. But cancelling an order may result in cancellation fees, require you to ship back things you got back, end. It is not “Undoing PlaceOrder”, rather that is a whole different and distinct business process, usually represented by another command: CancelOrder.

Another common issue that people have is the degeneration of the entire architecture to something like:

CommandExecuter.Execute(Command cmd);

To that I answer, more power to you! I love code that is composed of a lot of small classes all doing things about the same way. There is no easier way to look at a system, and that allows you to quite easily add additional functionality to the system easily. That said, mind how you handle routing in that scenario. I have seen people go into the “when a request comes to this URL, let us invoke the following commands” in XML. One of the reasons that people dislike this approach is how you actually call this. If just getting to the command executer is hard and involved, you lose a lot of the advantages.

This popped up in the mailing list, and I really dislike it. The notion of Composite Command. A command that can execute multiple commands. Now, from a programming point of view, I can easily see why you would want to do that. The PlaceOrderCommand operation is composed of a lot of smaller commands. But, and this is important, the notion of Composite Commands basically mean that you get the same thing as the PlaceOrderCommand, but you just lost the name. And naming is important. Almost as important, error handling is quite different between different business scenarios, and you sometimes end up with something like:

   1: var placeOrderCommand = new CompositeCommand(
   2:    new RegisterOrderCommand(),
   3:    new ReserveStockCommand(),
   4:    new ChargeCardCommand(),
   5:    new ShipOrderCommand()
   6: )
   7: {
   8:    Sequential = true,
   9:    StopOnError = true
  10: }

And this is simple, how do you handle an error in the ShipOrderCommand after you already charged the card, for example?

Design patterns in the test of time: Command

The command pattern is a behavioral design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time.

More about this pattern.

I adore this pattern. If this pattern had a paypal account, I would donate it money on a regular basis.

In general, the notion of encapsulating the method call into an object (like the functor sin C++) is an incredibly powerful idea, because is separate the idea of selecting what to invoke and when to invoke it. Commands are used pretty much every where, WPF is probably the most obvious place, because it actually have the notion of Command as a base class that you are supposed to be using.

Other variations, like encapsulating a bunch of code to be executed later (job / task), or just being able to isolate a complex behavior into its own object, is also very useful. I base quite a lot of my architectural advice on the notion that you can decompose a system to a series of commands that you can compose and shuffle at will.

Recommendation: Use it. Often. In fact, if you go so far as to say that the only reason we have classes is to have a nice vehicle for creating commands, you wouldn’t be going far enough.

Okay, I am kidding, but I really like this pattern, and it is a useful one quite often. The thing that you want to watch for are commands that are too granular. IncrementAgeCommand that is basically wrapping Age++ is probably too much, for example. Commands are supposed to be doing something meaningful from the scope of the entire application.

Design patterns in the test of time: Chain of responsibility

The chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.

More about this pattern.

It is actually quite common to see this pattern now-a-days using events. Something like CancelEventArgs and a CancelEventHandler to handle the FormClosing event of a Form.

We use Chain of Responsibility in RavenDB in several places, like this one:

foreach (var requestResponderLazy in currentDatabase.Value.RequestResponders)
{
  var requestResponder = requestResponderLazy.Value;
  if (requestResponder.WillRespond(ctx))
  {
    var sp = Stopwatch.StartNew();
    requestResponder.Respond(ctx);
    sp.Stop();
    ctx.Response.AddHeader("Temp-Request-Time", sp.ElapsedMilliseconds.ToString("#,# ms", CultureInfo.InvariantCulture));
    return requestResponder.IsUserInterfaceRequest;
  }
}

Note that we have moved on the the behavioral patterns, and those tend to have withstand the test of time much better, in general.

Other places where Chain of Responsibility is used is request routing and error handling. A common approach is to also have this done by delegating, where I am handling what I can and passing on to the next object if I don’t know how to handle a request.

Recommendation: This is still a very useful pattern. One thing to note is that it is effectively an O(N) operation with respect to the number of items in the chain that you have. As usual, do not overuse, but it is a really nice pattern.

Design patterns in the test of time: Proxy

A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.

More about this pattern.

Proxies are just about everywhere. Whenever you use NHibernate, WCF or Remoting – you are using proxies. In fact, proxies are such a success that they are literally baked into both the language and the platform. In .NET we have TransparentProxy and in Java has java.lang.reflect.Proxy.

At any rate, proxies are really useful, especially when you think about dynamic proxies. I am far less fond of static proxies, although we use them as well. Dynamic proxies are quite useful to add behavior, especially cross cutting behavior, at very little cost.

That said, one of the major issues that arises from using proxies is an inherit assumptions that the proxy is the same as its target. Commonly you see this happening with remote proxies, where it isn’t obvious that actually making the call is expensive as hell.

Proxies also tend to be used mostly for the infrastructure of your application, rather than for actual application code. In particular, business logic, rather than cross cutting concerns, is really hard to figure out / debug when you have it spread around in proxies.

Recommendation: Use it for infrastructure or cross cutting concerns. Try doing so using dynamic proxies, rather than by generating proxies by hand. Avoid putting business logic there and be aware that by using proxies you are hiding what is going on (that is pretty much the point), so doing non obvious things should be avoided.

Design patterns in the test of time: Flyweight

A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.

More about this pattern.

On the face of it, this patterns looks very much like something from the old ages. And indeed, most implementations of Flyweight are actually focused deeply on low memory conditions. I would actually argue that you need to consider very carefully when you want to do that.

That said, it is actually used fairly often in high performance places. In the .NET framework, the notion of string interning is one way to get flywieghts (although the problem is that you need to start with a string to get the intern string sort of mess things up). In both the profilers and in RavenDB, we have used variations on the Flyweight pattern.

In the profiler, we are mostly dealing with parsing data from the profiled system, and that means doing a lot of reading from a stream and creating objects. That created an unacceptable memory pressure on the system. We implemented a fairly complex system where we can read from the stream into a buffer, then get or create the string from it. We contributed the implementation back to the Protocol Buffers project. You can see the code here.

In RavenDB, we deal a lot with documents, and many times we find it useful to be caching a document. The problem with doing that is that you need to return something from the cache, which means that you have to return something mutable. Instead of copying all of the data all the time, the internal RavenDB data structures supports copy-on-write semantics, which means that we can easily create clones at basically no cost.

Recommendation: If you are in a perf optimization mode, and you worry about memory pressure, consider using this. Otherwise, like all optimizations, it should be left alone until you have profiler results that says you should consider this.

Midbook pattern crisis: Do NOT reach for that pattern

From a question in the mailing list:

How do you do to "rollback" an entity state supposing the following scenario.

public JsonResult Reschedule(string id, DateTime anotherDate)
{
            try
            {
                var dinner = session.Load<Dinner>(id);
                dinner.ChangeDate(anotherDate);
                schedulerService.Schedule(dinner); 

                return Json(new { Message = "Bon apetit!" });
            }
            catch (DinnerConcurrencyException ex) 
            {
                return Json(new { Message = ex.Message });
            }
}

// Base controller
protected void OnActionExecuted(ActionExecutedContext filterContext) 
{
      if(filterContext.Exception != null)
            return;
      session.SaveChanges();
}

The problem that I have is when the schedulerService throws a DinnerConcurrencyException, it is catched at the controller.

After all, the OnActionExecuted will call SaveChanges and persist the dinner with an invalid state.

The next post was:

I have already tried to use Memento Pattern like this:

try
{
    var dinner = session.Load<Dinner>(id);
    dinner.SaveState();
    dinner.ChangeDate(anotherDate);
    schedulerService.Schedule(dinner); 

    return Json(new { Message = "Bon apetit!" });
}
catch (DinnerConcurrencyException ex) 
{
    dinner = dinner.RestoreState();
    return Json(new { Message = ex.Message });
}

But didn't work, beacuse I think Raven has proxied my dinner instance.

And here is the Memento implementation:

[Serializable]
public abstract class Entity
{
    MemoryStream stream = new MemoryStream();

    public void SaveState()
    {
        new BinaryFormatter().Serialize(stream, this);
    }

    public T RestoreState<T>()
    {
        stream.Seek(0, SeekOrigin.Begin);
        object o = new BinaryFormatter().Deserialize(stream);
        stream.Close();

        return (T)o;
    }
}

You might notice that this create a new instance when you call RestoreState, and that has no impact whatsoever on the actual instance that is managed by RavenDB.

The suggested solution?

catch (DinnerConcurrencyException ex) 
{
    SkipCallingSaveChanges = true;
    return Json(new { Message = ex.Message });
}

No need for patterns here.

Midbook patterns crisis: Façade is and ain’t

I decided to comment to some of the comments in the blog in a full blown post, because they are quite important.

  • View Model is not a façade. It doesn’t allow any operation, and it doesn’t simplify things. It merely give you an easy access to aggregate information.
  • No, every class is not a Façade. I don’t care if “it provides simplified interface to a larger body of code”. If everything is a façade, then façade is meaningless.
  • No, Web Request is no a façade. Sure, it hides a lot of details about TCP, but that isn’t its point. Web Request implements HTTP spec, and that isn’t a façade at all.
  • Web Client / Tcp Client / Tcp Listener are facades – they drastically simplify how to work with sockets. Good facades, too, because when you need to do more, they don’t block you.
  • NHibernate ain’t a façade – it hides ADO.NET, sure, but it also does a lot more then just that.

The whole point of this series of posts was not to talk about patterns. If you want to do that, go ahead and read the books. My attempt is to go and talk about how the patterns are actually used. In practice, in real code.

Sure, in the real world, patterns aren’t used as per their text book definition. That doesn’t mean that we should look at the text book definition. That means that we need to look at how they are actually used! I am not writing a series of posts talking about the problems in the patterns, and that is important. I am writing about the problems in how people use them.

Design patterns in the test of time: Façade

A façade is an object that provides a simplified interface to a larger body of code, such as a class library.

More about this pattern.

The intent of the façade was good: to wrap APIs that are poorly designed in something shiny and nice.

In the real world, however, it is an evil pattern that is used to needlessly add abstractions for no particular reason. For example, look at this article.

Business Facade - Detailed View Data Access - Detailed View

That sound you just heard is your architecture, it is hiding in the closet, weeping silent tears about emotional and physical abuse that just doesn’t end.

I have yet to see a real case were façade was actually used properly. In most cases, people built a façade because That Is How We Do Things. And because of that, they ended up with things like the one above. It adds exactly nothing, and it horrifyingly complicates the code.

Recommendation: Avoid this, you really don’t need to do this most of the time, and most implementations are bad.

Design patterns in the test of time: Decorator

The decorator pattern is a design pattern that allows behaviour to be added to an existing object dynamically.

More about this pattern.

I don’t have a lot to say about this pattern.

Hipster Ariel - Decorator? Used it before it was cool

The decorator pattern is still just as useful if not more so as the time it was initially announced. It forms a core part of many critical function of your day to day software.

The most obvious example is the notion of Stream, where you often decorate a stream (Buffered Stream, Compressing Stream, etc). This example is valid not just for the .NET framework, I can’t think of a single major framework that doesn’t use the Stream abstraction for its IO.

Then again, the cautionary side, people try to use it in… strange ways:

   1: public abstract class CondimentDecorator : Beverage {}
   2:  
   3: public class Mocha : CondimentDecorator
   4: {
   5:     private Beverage m_beverage;
   6:  
   7:     public Mocha(Beverage beverage)
   8:     {
   9:         this.m_beverage = beverage;
  10:     }
  11:  
  12:     public override String Description
  13:     {
  14:         get
  15:         {
  16:             return m_beverage.Description + ", Mocha";
  17:         }
  18:     }
  19:  
  20:     public override double Cost()               
  21:     {                                      
  22:         return 0.20 + m_beverage.Cost();
  23:     }
  24: }

Something like this, for example, is a pretty bad way of doing things. It assumes a very fixed model of looking at the universe, which is just not true. Decorator works best when you have just a single I/O channel. When you have multiple inputs & outputs, decorating something becomes much harder.

In particular, implementing business logic like the one above in decorators make it very hard to figure out why things are happening. In particular, CachingDecorator is something that you want to avoid (better to use infrastructure or a auto caching proxy, instead).

Recommendation: It is a very useful pattern, and should be used when you actually have one input / output channel, because that is a great way to allow to dynamically compose the way we apply processing to it.

Design patterns in the test of time: Composite

The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

More on this pattern.

This post is supposed to come on the 1st of Nov or there about, which means that I’m going to do a small divergence into politics now. Here is an example of how the upcoming presidential elections in the states.

   1: public interface IVotingUnit
   2: {
   3:     int Weight { get;set; }
   4:     int CandidateId { get;set; }
   5: }
   6:  
   7: public class Voter : IVotingUnit
   8: {
   9:     [Obsolete("Racist")]
  10:     string Id { get;set; }
  11:  
  12:     int Weight { get;set; }
  13:  
  14:     int CandidateId { get;set; }
  15: }
  16:  
  17: public class WinnerTakesAllState : IVotingUnit
  18: {
  19:     string StateCode { get;set; }    
  20:  
  21:     int Weight { get;set; }
  22:     int CandidateId { get;set; }
  23:  
  24:     public void AddVote(Voter vote){
  25:         // calculate
  26:     }
  27: }

Yes, this is probably a bad example of this, but I find it hilarious.  The basic idea is that you can have an object that represent many other objects, but show the same external interface.

Composites are usually used for the more CS style of programming. Composites are very common in tree structures such as compiler AST or DOM. But beyond that, I can’t easily recall any real world usage of them in my applications. There are usually better alternatives, and you have to remember that when you speak about enterprise applications, loading / storing the data is just as important. And trying to implement the composite pattern under those circumstances will lead to a world of hurt.

Recommendation: If your entire dataset can easily fit in memory, and it make sense, go ahead. Most of the time, you probably should stay away.

Design patterns in the test of time: Bridge

The bridge pattern is a design pattern used in software engineering which is meant to "decouple an abstraction from its implementation so that the two can vary independently".The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

More about this pattern.

Bridge is quite complex, mostly because it is composed of Abstraction, Refined Abstraction, Implementor and Concrete Implementor. Here is a concrete example (pun intended):

  • Abstraction: CImage
  • Refined Abstraction: CBmpImage, CJpegImage
  • Implementor: CimageImp
  • Concrete Implementor: CWinImp, COS2Imp

In general, I don’t like complex things, and of the top of my head, I can’t think of a time when I used this approach. Until such time when I can see a really good reason why I would want to do something like this, I see very little reason to bother.

Recommendation: Avoid, there are simpler options to solving those sort of problems.

Design patterns in the test of time: Adapter

In computer programming, the adapter pattern (often referred to as the wrapper pattern or simply a wrapper) is a design pattern that translates one interface for a class into a compatible interface.

More about this pattern.

This pattern is the first of the first of the Structural Patterns in the G04 book, and for the most part, it is meant to be used solely when you are integrating two or more external systems / libraries. When I saw it used inside a system, it almost always a Bad Thing, mostly because inside a single system, you want to use one of the other structural patterns.

HttpContextWrapper is a good example of using this pattern, and it links back nicely to the previous discussion on Singletons. HttpContext.Current was an issue, because it didn’t allow easy overriding / mocking / testing. The new HttpContextBase class was introduced, but due to backward compatibility concerns, HttpContext’s base class could not be changed. The solution, introduce HttpContextWrapper implementation that adapts between the two.

Useful pattern, but all too often people try to use it to abstract things, and that is most certainly not what it is meant for.

Recommendation: Use when you need to integrate with code that you can’t change (3rd party, legacy, compatibility concerns) using a common interface, but avoid otherwise.

Design patterns in the test of time: Singleton

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

More about this pattern.

I won’t show code or diagrams here. If you don’t know the Singleton pattern, you probably don’t have any business reading this series. Go hit the books and then come back for the rest of my review.

Of the top of my head, I can’t think of a single pattern that has been as denigrated as the Singleton pattern. It has been the bane of testers anywhere, and just about any Singleton implementation had had to become thread safe, given the demands that we usually have from our apps.

That basically means that any time that you use a Singleton, you have to be damn sure that your code is thread safe.  When it isn’t, this becomes really painful. That along would be a huge mark against it, since multi thread proofing code is hard. But Singleton also got a bad rep because they create hidden dependencies that were hard to break. Probably the most famous of them was HttpContext.Current and DateTime.Now.

Singleton may have a tattered reputation and wounded dignity, but it is still a crucially important pattern. Most of the issues that people have with the Singleton aren’t with the notion of the single instance, but with the notion of a global static gateway, which means that it becomes very hard to modify for things like tests, and it is easy to create code that is very brittle in its dependencies on its environment.

Common workaround to that is to break apart the notion of accessing the value and the single nature of the value. So you typically inject the value in, and something else, usually the container, is in charge of managing the lifetime of the object.

Common use cases for Singletons include caches (which would be pretty bad if they didn’t stuck around) and the NHibernate’s Session Factory (which is very expensive to create).

Recommendation: The notion of having just a single instance of an object is still very important, especially when you use that single instance to coordinate things. It does means that you have multi threading issues, but that can be solved. It is a very useful pattern, but you have to watch for the pit falls (global static accessor that is used all over the place is one of the major ones).

Design patterns in the test of time: Prototype

Create objects based on a template of an existing object through cloning.

More about this pattern.

This is how it looks like:

Prototype Example

Surprisingly enough, there are very few useful concrete examples of this, even in the literature. A lot of the time you see reference to ConcreteImplA and ConcreteImplB.

The original impetus for the Prototype pattern was actually:

  • avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
  • avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.

That is actually quite interesting. As I mentioned in the Factory Method analysis post, I like the notion of using Factory Delegate (and thus avoiding subclassing) quite a lot. This is usually useful for behavioral objects, that contains little state (it would be more accurate to say that their state is behavior, such as a class that mostly contains delegate members for different things). But for those sort of things, you usually don’t really need to modify them after the fact, so there isn’t much of a prototype here.

The second reasoning is not relevant for most things today. The cost of new is so near zero to be effectively meaningless.

But something that isn’t mentioned about this pattern is that it is very useful for multi threading. The notion of being able to handle a cloned object that can be modified independently of its original is key in things like caches, as you can see in the code above. We make heavy use of that internally inside RavenDB, for example, although we choose a slight more complex (and performant) route.

A key observation about this is that Prototype assumes long lives objects. Because otherwise, there wouldn’t be the prototype instance to clone from. In wide variety of applications today, that is simply not the case. Most of our objects live only for a single request. And anything whose lifetime is longer than a single request is usually persisted to a stable storage, rendering the basis for the Prototype pattern existence moot.

Recommendation: This is still a useful pattern for a limited number of scenarios. In particular, the ability to hand out a copy of the instance from a cache means that we don’t have to worry about multi threading. That said, beyond this scenario, I haven’t found many other uses for this.

Design patterns in the test of time: Factory Method

Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.

More on this pattern.

Here is some sample code:

   1: public class MazeGame {
   2:   public MazeGame() {
   3:      Room room1 = MakeRoom();
   4:      Room room2 = MakeRoom();
   5:      room1.Connect(room2);
   6:      AddRoom(room1);
   7:      AddRoom(room2);
   8:   }
   9:  
  10:   protected virtual Room MakeRoom() {
  11:      return new OrdinaryRoom();
  12:   }
  13: }

This pattern is quite useful, and is in fairly moderate use. For example, you can take a look at WebClient.GetWebRequest, which is an exact implementation of this pattern. I like this pattern because this allows me to keep the Open Closed Principle, I don’t need to modify the class, I can just inherit and override it to change things.

Still, this is the class method. I like to mix things up a bit and not use a virtual method, instead, I do things like this:

   1: public class MazeGame {
   2:    public Func<Room> MakeRoom = () => new OrdinaryRoom();
   3: }

This allows me change how we are creating the room without even having to create a new subclass. In fact, it allows me to change this per instance.

I make quite a heavy use of this in RavenDB, for example. The DocumentConventions class is basically built of nothing else.

Recommendation: Go for the lightweight Factory Delegate approach. As with all patterns, use with caution and watch for overuse & abuse. In particular, if you need to manage state between multiple delegate, fall back to the overriding approach, because you can keep the state in the subclass.

Design patterns in the test of time: Builder

The intent of the Builder design pattern is to separate the construction of a complex object from its representation. By doing so, the same construction process can create different representations.

More about this pattern.

The sample code that usually comes with this pattern is something like this:

   1: PizzaBuilder hawaiianPizzaBuilder = new HawaiianPizzaBuilder();
   2: Cook cook = new Cook();
   3: cook.SetPizzaBuilder(hawaiianPizzaBuilder);
   4: cook.ConstructPizza();
   5: // create the product
   6: Pizza hawaiian = cook.GetPizza();

I find this sort of code to be extremely verbose and hard to read. Especially when we have a lot of options and things to do. Fluent Interfaces, however, are just an instance of the Builder pattern, and they are basically adding a modern API look & feel to the way we are actually constructing objects. Another thing to remember is that we are dealing with C#, and we have things like object initializers to do a lot of the heavy lifting for building objects. You should use that, for most cases.

NHibernate, for example, has the notion of a Builder, using the NHibernate.Cfg.Configuration object. It allows us to put all of the construction / validation code in one spot, and then the actual runtime code in a different place (and can assume a lot about its invariants). It also allows to do a lot of interesting things, like serializing the builder object (to save building time), which is something that you usually can’t / hard to do with real objects.

That said, you should be careful of code like the one listed above .What you have there is an overly abstract system. Requiring multiple steps to just get somewhere. If you find yourself feeding builders into builders, please stop and think about what you are doing. If you got there, you have not simplified the construction process.

Recommendation: This is still a very useful pattern. It should absolutely not be used if all you need to do is just setting some values. Reserve the Builder patterns where you actually have logic and behavior associated with the building process.

Design patterns in the test of time: A modern alternative to Abstract Factory–filtered dependencies

In my Abstract Factory post, I mentioned that I really don’t like the pattern, and in particular, code like this:

   1: static IGUIFactory CreateOsSpecificFactory()
   2: {
   3:    string sysType = ConfigurationSettings.AppSettings["OS_TYPE"];
   4:    if (sysType == "Win") 
   5:    {
   6:        return new WindowsFactory();
   7:    } 
   8:    else 
   9:    {
  10:        return new MacFactory();
  11:    }
  12: }

One of the comments mentioned that this might no be ideal, but it is still better than:

   1: if(RunningOnWindows)
   2: {
   3:     // code
   4: }
   5: else if(RunningOnMac)
   6: {
   7:    // code
   8: }
   9: else if(RunningOnLinux)
  10: {
  11:    // code
  12: }

And I agree. But I think that, as the comment mentioned, a far better alternative would be using the container. You can do this using:

   1: [OperationSystem("Windows")]
   2: public class WindowsFactory : IGUIFactory
   3: {
   4: }
   5:  
   6: [OperationSystem("Linux")]
   7: public class LinuxFactory : IGUIFactory
   8: {
   9: }
  10:  
  11: [OperationSystem("Mac")]
  12: public class MacFactory : IGUIFactory
  13: {
  14: }
  15:  

Then you just need to wire things through the container. Among other things, this means that we respect the open / closed principle. If we need to support a new system, we can just add a new class, we don’t need to modify code.

Remember, the Go4 book was written in the age of C++. Reflection didn’t exists, and that means that a lot of patterns do by hands things that can happen automatically.

Design patterns in the test of time: Abstract Factory

The essence of the Abstract Factory method Pattern is to "Provide an interface for creating families of related or dependent objects without specifying their concrete classes".

More about this pattern.

Here is some sample code:

   1: static IGUIFactory CreateOsSpecificFactory()
   2: {
   3:     string sysType = ConfigurationSettings.AppSettings["OS_TYPE"];
   4:     if (sysType == "Win") 
   5:     {
   6:         return new WindowsFactory();
   7:     } 
   8:     else 
   9:     {
  10:         return new MacFactory();
  11:     }
  12: }

I am in two minds about this pattern. On the one hand, we have pretty damning evidence that this has been really bad for the industry at large. For details, you can see Why I Hate Frameworks post. When I first saw that, just shortly after reading the Go4 for the first time, I was in tears from laughing. But the situation he describe is true, accurate and still painful today.

Case in point, WCF suffers from a serious overuse of abstract factories. For example, IInstanceProvider (and I just love that in order to wire that in you usually have to implement IServiceBehavior).

As the I Hate Frameworks post mentioned:

Each hammer factory factory is built for you by the top experts in the hammer factory factory business, so you don't need to worry about all the details that go into building a factory.

Awesome, or not, as the case may be.

Then again, it is a useful pattern. The problem is that in the general case, creating objects that create objects (that create even more objects) is a pretty good indication that your architecture is already pretty hosed.  You should strive to an architecture that has minimal amount of levels, and an abstract factory is a whole new level even on its own.

Recommendation: Avoid if you can. If you run into a place where you think that needs this, consider if you can simplify your architecture to the point where this is not required.

Design patterns in the test of time

Design Patterns: Elements of Reusable Object-Oriented Software

Amazon tells me that I purchased this book in Sep 2004, and have since then misplaced it, for some reason. I remember how important this book was to shaping how I thought about software. For the first time, I actually have the words discuss what I was doing, and proven pathways to success. Of course, we all know that… it didn’t end up being quite so good.

In particular, it led to Cargo Cult Programming. From my perspective, it looks like a lot of people made the assumption that their application is good because it has design patterns, not because design patterns will result in simpler code.

Now, this book came out in 1994. And quite a bit have changed in the world of software since that time. In this series, I am going to take a look at all those design patterns and see how they hold up in the test of time. Remember, the design patterns were written at a time where most software was single user client applications (think Win Forms, then reduce by nine orders of magnitude), no web or internet, no multi threading, very little networking, very slow upgrade cycles and far slower machines. None of those assumptions are relevant to how we build software today, but they form the core of the environment that was relevant when the book was written. I think that it is going to be interesting to see how those things hold up.

And because I know the nitpickers, let me setup the context. We are talking about building design patterns within the context of .NET application, aimed at either system software (like RavenDB) or enterprise applications. This is the context in which I am talking about. Bringing arguments / options from additional contexts is no relevant to the discussion.

I am also not going to discuss the patterns themselves at any depth, if you want that, go and read the book, it is still a very good one, even though it came out almost 20 years ago.