Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
By open for extension, this principle means the ability for an entity to be adapted to meet the changing needs of an application. By closed for modification, this principle means that the adaptation of an entity should not result in modification of the entity’s source.
Interpretation: Open/Closed is for any given object; that object should not need to be modified in order to be used.
In JavaScript it is often used in situations where you want to extract functionality from a large function into other functions. In other words, if you are having to change a function or class constantly due to updates or changes in requirements that’s a sign of modification. Instead extract the a base/super class/type and extend the behavior in child or subtype objects.
Seems easy but one of my mentors pointed out my violation of the Open/Closed principle when I added a compare method to the Array prototype in JavaScript. My reply was ‘don’t you want to be able to compare arrays as part of the Array Prototype’? Mentor’s answer (which rocked my world): “In this case you’re modifying the Array.prototype (globally) in order to add a convenience method. It could be considered "Extending” the Array class; but time and again this pattern of adding functionality onto an existing object/namespace/class at runtime bites people in the ass.“
He then pointed me toward underscore.js which is a library that has extended convenience JavaScript methods. Lesson: Don’t mess with something that works and is expected to respond in a specific manner.
Stay connected