Monday, June 21, 2010

Code Tip - 6/21/2010

If you want to create an immutable object but want to make sure that you don't have to create a different constructor for every combination of parameters, a consistent state, and readability, use the Builder pattern.

For an example, in my Stock application, I will have a Stock object that will not change throughout algorithm run.  It will always have the same name, description, dates, current price, and symbol.  The Stock object will always have a symbol but may not have some or all of the other parameters (or some combination of).  Here's the builder pattern implementation to create this object:

public class Stock
{
  private final int id;
  private final String stockName;
  private final String description;
  private final String symbol;
  private final float price;
  private final Date date;


  public static class StockBuilder
  {
    private final int id;
    private final String symbol;



    private String stockName;
    private String description;
    private float price;
    private Date date;



    public StockBuilder(int id, String symbol)
    {
      this.id = id;
      this.symbol = symbol;
    }


    public StockBuilder StockName(String name)
    {
      this.stockName = name;
      return this;
    }





    public StockBuilder Description(String description)
    {
      this.description= description;


      return this;
    }





    public StockBuilder Price(float price)
    {
      this.price= price;


      return this;
    }


    public StockBuilder StockName(String name)
    {
      this.stockName = name;
      return this;
    }


    public StockBuilder StockDate(Date date)
    {
      this.date= date;
      return this;
    }

    public StockBuilder Build()
    {
      return new Stock(this);
    }
  }


  private Stock(StockBuilder builder)
  {



    this.id = builder.id;
    this.symbol = builder.symbol;


    this.stockName = builder.stockName;
    this.description = builder.description;
    this.price = builder.price;
    this.date = builder.date;



  }


And now to initialize the Stock object:


Stock stock = new Stock.StockBuilder(5,"GOOG").StockName("Google").Price(500).Build();


Stock nextStock = new Stock.StockBuilder(5,"MSFT").Price(70.5).Description("Microsoft corporation description").Build();

No comments:

Labels