Thursday, August 28, 2008

Object oriented design

Today, I was listing to Hal Helms and Jeff Peters discuss object oriented design. They were talking about inheritance -vs- composition. The main point was how composition has a is favored over inheritance, is a. Ive been hearing this for awhile, but have not always understood, probably because its a little abstract, since im not doing much in the way of new object design or at least not with extending base classes.

One concept was that base classes are really not ever instantiated, but extended. This notion was further described this way:

A goal of class programming, remember this is the model layer, not the view of controller, is to create stable reusable objects where commonality is captured in a base class that can be inherited or extended by a more specific class. Another way to describe this base class is as a super class.

The goal is to allow base classed to be easily extended (composition) to incorporate new behavior without modifying existing code. This creates designs that are resilient to change and flexible enough to take on new functionality to meet changing requirements.

Design principle:
Classes should be open to extension and closed to modification.

These concepts where discussed around the context of the Decorator Pattern.

Remember, when you abstract the differences by composition, you are adding complexity to the application. Dont forget to think in terms of trade offs. Nothing is free, when you build more extensible code, classes, by following this excellent principle, you are adding more complexity to your logic. Only apply the "open closed" principle where needed.

No comments: