Refactoring and Open / Closed principle

open-closeprogramming practicesrefactoring

I have recently being reading a web site about clean code development (I do not put a link here because it is not in English).

One of the principles advertised by this site is the Open Closed Principle: each software component should be open for extension and closed for modification. E.g., when we have implemented and tested a class, we should only modify it to fix bugs or to add new functionality (e.g. new methods that do not influence the existing ones). The existing functionality and implementation should not be changed.

I normally apply this principle by defining an interface I and a corresponding implementation class A. When class A has become stable (implemented and tested), I normally do not modify it too much (possibly, not at all), i.e.

  1. If new requirements arrive (e.g. performance, or a totally new implementation of the interface) that require big changes to the code, I write a new implementation B, and keep using A as long as B is not mature. When B is mature, all that is needed is to change how I is instantiated.
  2. If the new requirements suggest a change to the interface as well, I define a new interface I' and a new implementation A'. So I, A are frozen and remain the implementation for the production system as long as I' and A' are not stable enough to replace them.

So, in view of these observation, I was a bit surprised that the web page then suggested the use of complex refactorings, "… because it is not possible to write code directly in its final form."

Isn't there a contradiction / conflict between enforcing the Open / Closed Principle and suggesting the use of complex refactorings as a best practice? Or the idea here is that one can use complex refactorings during the development of a class A, but when that class has been tested successfully it should be frozen?

Best Answer

I think of the Open-Closed principle as a design goal. If you end up having to violate it, then that means your initial design failed, which is certainly possible, and even likely.

Refactoring means you're changing the design without changing the functionality. Likely you're changing your design because there's a problem with it. Perhaps the problem is that it's difficult to follow the open-closed principle when making modifications to the existing code, and you're trying to fix that.

You might be doing a refactoring to make it possible to implement your next feature without violating the OCP when you do it.

Related Topic