Enterprise Integration Zone is brought to you in partnership with:

Nadav is a software development group leader. He gained experience in all aspects of software development including requirement analysis, software design and implementation. He has 3 kids and a fish. Nadav is a DZone MVB and is not an employee of DZone and has posted 8 posts at DZone. You can read more from them at their website. View Full User Profile

The Wizard Design Pattern

03.01.2013
| 4088 views |
  • submit to reddit

We all love wizards.... (Software wizards I mean). We are always happy to jump on those ''Next" buttons like we were dancing the funky chicken on our… well you get the point. So today we bring you your beloved wizard into your coding experience. Let's jump right into an example.

Say you want to design a ConservativePerson class.

view sourceprint?
import java.util.List; 
class ConservativePerson{ 
  
    private boolean isVirgin; 
    private boolean isMarried; 
    private List<string> children; 
  
    ConservativePerson(boolean virgin, boolean married, List<string> children) { 
        this.isVirgin = virgin; 
        this.isMarried = married; 
        this.children = children; 
    } 
  
    public boolean isVirgin() { 
        return isVirgin; 
    } 
    public boolean isMarried() { 
        return isMarried; 
    } 
  
    public List<string> getChildren() { 
        return children; 
    } 
} 

As such it has some constrains.

  • He must be married before he can be... well, not a virgin.
  • He can't be a virgin before he can have children (as far as we know).

In the old days, which is basically all days until today..., you would probably define all kinds of modifiers methods for this class which will throw an exception in case of invariant invalidation such as NotMarriedException and VirginException. Not anymore.

Today we will do it by using the Wizard Design Pattern. We use a fluent interface style and utilize the power of a modern IDE to create a wizard-like feeling when building a ConservativePerson object. We know, we know, stop talking and show us the code... but before we will present the wizard code we will show you it usage so you will get a grasp of what we are talking about...

view sourceprint?
public class Main { 
public static void main(String[] args) { 
    ConservativePersonWizardBuilder wizard = new ConservativePersonWizardBuilder(); 
    ConservativePerson singlePerson = wizard. 
            createConservativePerson(). 
            whichIsSingle(). 
            getObject(); 
    ConservativePerson familyManPerson = wizard. 
            createConservativePerson(). 
            whichIsMarried(). 
            andNotVirgin(). 
            andHasChildNamed("Noa"). 
            anotherChildNamed("Guy"). 
            lastChildName("Alon"). 
            getObject(); 
  } 
  
} 

Now, it may look just like an ordinarily fluent interface, but the cool thing here is that a method is available for calling only if the current object state allows it. This means you will not be able to call the method andNotVirgin if you haven't called the method whichIsMarried.

See the following set of screen shots:


and after we state he is married we can:


Here is the wizard code. I urge you to copy/paste it to your IDE and give it a try by building an object with it.

view sourceprint?
import java.util.ArrayList; 
  import java.util.List; 
   
   public class ConservativePersonWizardBuilder { 
     private boolean isVirgin; 
     private boolean isMarried; 
     private List<String> children = new ArrayList<String>(); 
       
     public SetMarriedStep createConservativePerson(){ 
         return new SetMarriedStep(); 
     } 
   
     class SetMarriedStep { 
        public SetVirginStep whichIsMarried(){ 
             isMarried = true; 
             return new SetVirginStep(); 
         } 
    
         public FinalStep whichIsSingle(){ 
             isMarried = false; 
             return new FinalStep(); 
         } 
     } 
  
     class SetVirginStep { 
         public AddChildrenStep andNotVirgin(){ 
             isVirgin = false; 
             return new AddChildrenStep(); 
         } 
         public FinalStep butStillAVirgin(){ 
             isVirgin = true; 
             return new FinalStep(); 
         } 
     } 
  
     class FinalStep { 
         public ConservativePerson getObject(){ 
             return new ConservativePerson(isVirgin, isMarried, children); 
         } 
     } 
  
     class AddChildrenStep { 
         public AddChildrenStep andHasChildNamed(String childName) { 
             children.add(childName); 
             return new AddChildrenStep(); 
         } 
         public AddChildrenStep anotherChildNamed(String childName) { 
             children.add(childName); 
             return new AddChildrenStep(); 
         } 
         public FinalStep lastChildName(String childName){ 
             children.add(childName); 
             return new FinalStep(); 
         } 
     } 
 } 

As you can see the wizard consists of several steps. Each step is represented by a dedicated inner class. Each step reveals the legal available operations by its methods. Each method will then return a new step according to the change it has made. This way an attempt to create an illegal object will be detected at compile time instead of runtime.

This pattern is actually being used in our production code. One example that comes to mind is the MediaJob class. This class describes a manipulation on some media files. In order to submit a job to the system, one has to create a MediaJob object. The problem is that this object has many parameters that could be assigned with contradicting values that create an illegal object state. By using the Wizard pattern, one can easily build a legal job without the need to know the entire (and complicated…) set of constrains.

That is all for now. Hope you'll give it a try..... 

view sourceprint 

Published at DZone with permission of Nadav Azaria, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Alexandru Repede replied on Fri, 2013/03/01 - 10:53am

 No comments for this beautifull coding? What a shame! :-)

Well, sir, very nice DSL for something as simple as a Builder.


Have you considered building more advanced DSLs, with code generation?

One usecase for this would be, when you have many options on each level and, sometimes but now always, replicate option across diferent branches on the same level.

I will give an example: I want to build a PaymentMethod that consists of Country, Currency, CardType. Say I have many countries (USA, Germany, France, Japan), then some currencies (USD, EUR, JPY) and some cards (Mastercard, Visa, Maestro). You can see how these are options:

  • Germany.Euro.Visa, Germany.Euro.Mastercard
  • France.Euro.Visa
  • Usa.Usd.Visa

And you might notice how Euro is dubled for 2 countries, while cards can be used for all (or perhaps I want to even not enable Visa for Japan).

Now, if we your company sells internationally, you might have shitloads of countries, somewhat many currencies, and some card types. And you don't want to really build this by hand, thus the code generation (but it will still be a DSL).

I would love to see an example... :D


Nadav Azaria replied on Fri, 2013/03/01 - 11:34am in response to: Alexandru Repede

Actually I have thought of an example. I plan to define/find a declarative language which describe the command line parameters of a console application (like grep). It should include the parameters descriptions, their dependencies etc. Then develop a compiler which will generate a "Wizard" class for building a legal command line. 

Brennan Spies replied on Sat, 2013/03/02 - 5:38pm

It's essentially the Builder design pattern crossed with the State pattern. I've used this one myself (in proxy4j), the use of which was inspired by Guice.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.