Sunday, April 05, 2009

A simple example of the power of polymorphism

I often see codes written by the less experienced programmers that contain a lot of if/else blocks where they do something differently with different types of objects. For example,

public class Coordinator {

public void doSomethingWithList(List list) {
for (Object o : list) {
if (o instanceof A) {
A a = (A) o;
doSomethingWithA(a);
}
else if (o instanceof B) {
B b = (B) o;
doSomethingWithB(b);
}
// and so forth for class C, D, E, F, ...
}
}
}

In the above codes, the current method is making all the coordination work as it determines what to do with different types of objects. By introducing a superclass or an interface, we can refactor the code to something more extensible, and you don't have to change the loop each time a new class is introduced.

First, declare an interface (or a superclass that all the different types of objects will inherit from):

public interface Foo {
public void workWith(Coordinator coordinator);
}

Change types A, B, C, D, ... to implement this interface:

public class A implements Foo {
public void workWith(Coordinator coordinator) {
// do something specific to the A class
}
}

Change Coordinator.doSomethingWithList() to:

public void doSomethingWithList(List<Foo> list) {
for (Foo o : list) {
o.workWith(this);
}
}

You'll never have to change the loop again when you introduce new types. The Coordinator will invoke the workWith() method polymorphically since all implementations of Foo must define that method.

No comments: