Tuesday, May 30, 2006

Nice factory method implementation

I have been working with a colleague of mine Nelutzu to refactor some code in a project. We have installed some metrics plugin in Eclipse and we started to purify he code (as we had some problems that the metrics spotted out)

One of the problems was the large number of branches in a factory method so Nelutzu has refactored it in a very nice way:
class FooFactory {
    private static HashMap items = new HashMap();
    static {
        items.put("foo1", new Foo1());
        items.put("foo2", new Foo2());
        items.put("foo3", new Foo3());
    public static Foo getFooProduct(String fooName) {
        return items.get(fooName).getClass().newInstance();  
Voila, no if or switch while creating the objects. Nice work, Nelutzu!

No comments:

Post a Comment