The Wizard Design Pattern

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.

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…

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.

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….. We plan to write a more formal description of it (GOF style) in the near future.

References:  The Wizard Design Pattern  from our JCG partner Nadav Azaria & Roi Gamliel at the DeveloperLife

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

2 Responses to "The Wizard Design Pattern"

  1. niklasplessing says:

    how about this pattern im comparison. seems much more convenient…
    http://refactormycode.com/codes/194-fluent-builder

  2. Jan Stadler says:

    Very nice, thx

Leave a Reply


5 − two =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books