Saturday, June 19, 2010

Code tip - 6/19/2010

x
This one's an oldie.  Originally from Effective Java by Josh Bloch.

Use static factory methods instead of constructors when creating an object.

Reasons why:

  • Method names describe the instantiation of the object much simpler than a constructor.
public class MyObject implements IObject
{
   public MyObject()
   {
      //logic
   }

   public MyObject(string param1)
   {
      //some other logic; however, besides the documentation, no way to tell what the difference between this constructor and the previous one is
   }
}
=============================================
public class MyObject implements IObject
{
   private MyObject() {} //no ability to call a constructor outside the class

   public static MyObject getInstanceDefault()
   {
      return new MyObject();
   }

   public static MyObject getInstanceWithName(string param1)
   {
      MyObject obj = new MyObject();
      obj.setName(param1);
   }
}

constructor instantiation:
IObject m = new MyObject();
IObject m1 = new MyObject(name);

factory method instantiation:
IObject m = MyObject.getInstanceDefault();
IObject m1 = MyObject.getInstanceWithName(name);
  • Can return an object that's a subtype of the current type
public class MyObject implements IObject
{
   public MyObject()
   {
      //logic
   }
}
=============================================
public class MyObject implements IObject
{
   public MyObject() {} 
}

public class MyOtherObject implements IObject



{
   public MyOtherObject() {} 
}

public class MyObjectProvider
{
   List list = new ArrayList();

   public static void AddNewObject(IObject obj)
   {
      this.list.add(obj);
   }

   public static IObject getInstance()
   {
      if(list.Size() == 0)
          throw new Exception();
      else
      {
          IObject obj = this.list.get(0);
          this.list.remove(0);
          return obj;
      }
   }

}

constructor instantiation.  Can ONLY return object of MyObject type:
IObject m = new MyObject();

factory method instantiation:
prep:
MyObjectProvider.AddNewObject(new MyObject());



MyObjectProvider.AddNewObject(new MyOtherObject());

IObject m = MyObjectProvider.getInstance(); //returns MyObject type
IObject m1 = MyObjectProvider.getInstance(); //returns MyOtherObject type

    No comments:

    Labels