Tuesday, December 6, 2011

Encapsulating the subclass creation in superclass

One of the common mistake that the programmers make it to instantiate the subclass directly rather than by the common interface. Lets explain it by a simple example. Say you have Animal , Tiger, Lion, Mouse and Bird as the classes. When you will design you will make Animal as the super class and Tiger, Lion, Mouse and Bird as its subclasses. Say Tiger has its own constructor. The client instantiate using
Tiger tig = new Tiger();
What is wrong with this? According to design principle one should always program to an interface. Something like this
Animal tig = new Tiger();
But why ? The basic reason for that is once developers write code that’s talks directly to the subclass type rather than through its common interface then its common tendency to change the subclass code in response to the needs of the client. And this will result into a number of special cases logic in the subclasses and will lead to maintenance problem.
How to restrict this ?
The answer to this is to encapsulate the creation of subclasses in the superclass. Something like this in the Animal abstract class add a method like
public abstract class Animal {
public Animal (){}
public static Animal createTiger(){return new Tiger()}
}
In Tiger subclass do something like this
public class Tiger{
protected Tiger(){}
}
What we have done is to modify the constructor of Tiger to provide it with protected access and have a creation method in the Animal. This will solve a lot of problem regarding the maintenance of code in the future.

No comments: