Sunday, February 1, 2009

How to discover a new Design Pattern ?

Design Patterns are found after hard work and experience. Every situation is different, and good judgment is needed to know when to use one.

Thankfully many patterns have been cataloged already. But what if you can't find a pattern for your problem ? The answer would be to discover a new one.

Patterns aren't fixed in stone. You may combine them, alter them, and adapt them for your unique situation. Whether your new pattern utilizes existing ones doesn't matter, the underlying principles for finding the pattern still remains the same.

I've made a list of principles for discovering a new design pattern below:


  1. Encapsulate what varies

  2. Favour composition over inheritance

  3. Program to interfaces, not implementations


Encapsulate what varies


The idea is to capture code that changes often and make it a reusable component. First you'll need to determine what is changing all the time, and then later make logical groupings of the code that changes.

Favour composition over inheritance


Beware of making everything an "IS-A" relationship. Sometimes a "HAS-A" relationship would be more beneficial. In fact it's better to favour "HAS-A" associations over "IS-A" associations whenever possible. Why do I say that ? Well ... "HAS-A" associations are related to encapsulations; you're capturing a sample of code and injecting it into another class as a property. If we were to make the property field an interface instead, we would be able to interchangeably inject several different implementations. This is an ideal property for creating reusable components. You might be thinking I'm refering to the strategy pattern in particular, however the underlying principle applies to all other patterns: "We want to make a seperate reusable component, which implies a seperate class with its own interface".

Program to interfaces, not implementations


Whenever a composition is created, it makes logical sense to extract an interface (good object-oriented programming). Thus the opposite is also true; program to an interface and you'll end up with several small reusable components (in theory of course ;)

 

0 comments: