Thursday, November 27, 2008

An interface/generalization design pattern

Interfaces are useful for specifying a contract that one or many classes may realize. Generalization is useful for a similar purpose. If class A is inherited by class B, all the structural and behavioral features of class A because features of class B. In effect, class B realizes the interface of class A.

A good software development practice would then be to create a base class for each interface in your application that realizes each interface respectively. This way, any subsequent classes that are implemented can realize interfaces in your application in one of two ways. The first, directly realize the interface using the programming language constructs. The second, generalize the base class that corresponds to the interface you wish to realize.

By creating a base class for each interface that is ready to use by subclasses, you can implement some of the simpler methods in the base class. Subclasses may then only need to implement one or a few methods while still indirectly realizing the interface. One can argue that the interface level can be cut out completely. You could. The interface simply serves as an abstract conceptual tool for developers. You could only use generalization and override methods as needed. Both ways are valuable object oriented design but I think you'll find combining generalization and interfaces much more flexible and fun.

No comments :

Post a Comment