Friday, June 29, 2012

Builder design pattern in Java is a creational pattern i.e. used to create objects, similar to factory method design pattern which is also creational design pattern. Before learning any design pattern I suggest find out the problem a particular design pattern solves. Its been well said necessity is mother on invention. learning design pattern without facing problem is not that effective, Instead if you have already faced issues than its much easier to understand design pattern and learn how its solve the issue. In this Java design pattern tutorial we will first see what problem Builder design pattern solves which will give some insight on when to use builder design pattern in Java, which is also a popular design pattern interview question and then we will see example of Builder design pattern and pros and cons of using Builder pattern in Java.

What problem Builder pattern solves in Java

As I said earlier Builder pattern is a creational design pattern it means its solves problem related to object creation. Constructors in Java are used to create object and can take parameters required to create object. Problem starts when an Object can be created with lot of parameters, some of them may be mandatory and others may be optional. Consider a class which is used to create Cake, now you need number of item like egg, milk, flour to create cake. many of them are mandatory and some of them are optional like cherry, fruits etc. If we are going to have overloaded constructor for different kind of cake then there will be many constructor and even worst they will accept many parameter.

Problems:

1) too many constructors to maintain.

2) error prone because many fields has same type e.g. sugar and and butter are in cups so instead of 2 cup sugar if you pass 2 cup butter, your compiler will not complain but will get a buttery cake with almost no sugar with high cost of wasting butter.

You can partially solve this problem by creating Cake and then adding ingredients but that will impose another problem of leaving Object on inconsistent state during building, ideally cake should not be available until its created. Both of these problem can be solved by using Builder design pattern in Java. Builder design pattern not only improves readability but also reduces chance of error by adding ingredients explicitly and making object available once fully constructed.

Builder design pattern in Java – Pros and Cons

Live everything Builder pattern also has some disadvantages, but if you look at below, advantages clearly outnumber disadvantages of Builder design pattern. Any way here are few advantages and disadvantage of Builder design pattern for creating objects in Java.

Advantages:

1) more maintainable if number of fields required to create object is more than 4 or 5.

2) less error-prone as user will know what they are passing because of explicit method call.

3) more robust as only fully constructed object will be available to client.

Disadvantages:

1) verbose and code duplication as Builder needs to copy all fields from Original or Item class.

When to use Builder Design pattern in Java

Builder Design pattern is a creational pattern and should be used when number of parameter required in constructor is more than manageable usually 4 or at most 5. Don't confuse with Builder and Factory pattern there is an obvious difference between Builder and Factory pattern, as Factory can be used to create different implementation of same interface but Builder is tied up with its Container class and only returns object of Outer class.

That's all on Builder design pattern in Java. we have seen why we need Builder pattern , what problem it solves, Example of builder design pattern in Java and finally when to use Builder patter with pros and cons. So if you are not using telescoping constructor pattern or have a choice not to use it than Builder pattern is way to go.

My question is: if I write new Cake.Builder().build(); the code will compile and execute but I will lose the benefit of having a fully constructed object, it is similar to call the default constructor. Is there a more elaborate version of this pattern that will check parameters before calling the constructor of do we have to do it on our own ?

@Anonymous, You have raised a valid scenario, If Any object has combination of mandatory and optional parameter than before building, build method can check if those parameters are provided or not and it can throw Exception, similar to IllegalArgumentException.

@Anonymous and @Javin PaulWhat if, instead of throwing exceptions, the API is done as such that the builder dictates which method is possible to call or not? I described how, using the step builder pattern, in an article here : http://rdafbn.blogspot.co.uk/2012/07/step-builder-pattern_28.html

I see "this" is returned from all builder-parts, but how does that work, the builder is a static class and static classes can't have a "this" reference. So what am I missing.(I understand the pattern otherwise, it's just the "this" reference I don't get=

What's the point in complaining about whether this is strictly a Builder or not? The version here could be called a "Light Builder" that combines Director and Product but still reduces errors and makes code more fluent.My thanks to the author.

If there are defaults that are included for every instance of cake that is to be returned, then change the access modifiers of all required methods to private, and include them in the method body of the build() method. That way, whenever build() is invoked, there will be a default object initialized. Also, since those methods are private but included in the build() method, the method chaining is cut back a little, and the invoker doesn't need to know which methods of Builder are required and which aren't.

I really like your technique of the embedded builder object and it's fluent (as in Google's fluent) style of taking parameters and using them to build the final instance of the object. That's neat.

However, this version of the "builder" pattern is pretty different from the builder pattern that you would see in the original Gang of Four book. There they view the pattern as a form of translation between a set of initialization data and several possible outputs for the same data. Their example is reading an RTF file and having different converters produce several different output formats of that same file (ASCII, TeX, etc.).

In your case you're always producing the same output class as a result of the building process, you've just ensuring avoiding inconsistency, making it easier to build the object, etc.

If I were to ask you about the builder pattern from the GoF book I wouldn't see those as being that similar.

I guess your pattern panned out very well. But I want you to elaborate more on the return types. I feel their use without explanation in this pattern, it seems, both mystery and indulgence- on your part- to me. Your answer will offer a better perspective for a beginner like me.