Object-oriented – Open/Closed principle and reopening Ruby Classes

designdesign-patternsobject-orientedruby

In OOP there is the Open/Closed principle that states that

"software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".

Taking in consideration that in Ruby it is to possible to reopen a class, don't you think that this breaks the Open/Closed principle?

When do you think we should favor reopening classes instead of just extending them?

What do you think that are pitfalls in reopening classes?

Best Answer

Ruby's open classes provide a way to programatically build up complex classes. For complicated libraries this makes configuration easier, and code smaller and more maintainable. If you ever meet a Lisp programmer, they will talk you ear off about how wonderful it is to use code to write code.

This power can be used for both good and evil. The practice of Monkey Patching functionality into a class is expedient, but is also a form of technical debt that will make it harder to stay current and maintain code.

A good rule of thumb is that a class should be reopend only by the person (group) that originally wrote it. If others are feeling then need to reopen one of your classes, that is probably a sign that it needs to be refactored so it is more configurable, that is open for extension. This is the D of SOLID.