17 June, 2008

Design Patterns: Why use the Open/Close Principle, SOC and COR patterns...

Having read about the "Open/Close" principle (Open for extension/Closed for modification); I kind of found it difficult to grasp initially - but as I've been thinking more and more about it - the better I like it.

It really makes a lot of sense to keep your classes small and focused instead of having a "large" class doing tons of things. The Open/Close principle also supports very well one of my other favorite design principles: "Separation of Concern" (SOC). The SOC design pattern advocates that a class should do one thing only - hence it is focused! The class should have only "one reason to change" - yes, if the class does only one thing then it has only one reason to change :-)

A good example on the small and focused class factoring way of thinking is the pattern: "Chain of Responsibility" (COR). This pattern encompasses the "separation of concerns" very well as every link in the "chain" is responsible of one thing only. In addition it makes it very simple to extend this system by adding a new link to the Chain (can you see the reference to Open/Close here?). Furthermore the existing links are simple and thereby (should be!) closed for modification (again Open/Close is here!).

I've begun using this COR pattern more and more frequently as it makes development more simple in the sense that every link is: One class - One purpose. It does however make the initial setup a bit more complex than having a switch-statement in your code, but it is a good "investment" to factor your logic in focused classes. Every time I attempt to jump over the fence and use a switch-statement, I often find myself changing this code at a later point in time as "unforeseen" changes are emerging.

As principal illustration of the COR is seen below:

COR

No comments: