Wednesday, April 16, 2014

Session 3 - The Open/Closed Principle

<Meh>

In this session, we look at the second SOLID principle, the Open/Closed Principle (OCP).

I always couple this and the SRP (Single Responsibility Principle) together because in most cases, you can't implement the one without other.

There's not much I can say that I didn't already say in the previous post. I've always felt the the SRP is driven by the OCP and depending on what the future of a class might look like, you'll apply the OCP and SRP accordingly.

I always make a point of showing my design to the resident architect (if I'm not in charge of architecture of a solution). The architects in the enterprise product space tend to know the next four to five steps for a particular system, product or department. It's important that when you create/refactor code to adhere to the OCP, that you you take that into consideration.

Most interesting thing about this session for me was the two different approaches to inheritance for OCP between Bertrand Meyer and Robert C Martin. Martin's is again very purest and in my humble opinion, the better approach. But you cannot deny the merit of Meyer's approach. It's very practical especially when you need to extend product code that was never designed to be extended.

We also take a quick look at C# 3.0's Extension Methods. It also is very handy when you need to introduce new methods to classes that weren't designed to be extended. Although with that and Meyer's approach, code management might be come an issue if the changes aren't implemented properly.

With OCP, like with any other principle, there are various risks when implementing it. The main risk that comes to mind is code coupling. With composition (using interfaces: http://en.wikipedia.org/wiki/Composition_over_inheritance), you get very good decoupling of code. With class inheritance, your classes are tightly coupled and testing individual classes becomes more difficult. This is again one of the many factors that need to be weighed when designing new code or extending existing code.

For this session, you can find the various stuff here:
Presentation: http://www.slideshare.net/DeonMeyer/code-like-a-ninja-session-3-openclosed-principle
Code: https://github.com/sheepworx/training

Next up is Liskov's Substitution Principle

</Meh>

No comments:

Post a Comment