On NetTuts.com today they continue their look at the SOLID development principles with the next letter in the sequence - O for Open/Closed Principle. The first part of the series, covering "S" (the Single Responsibility Principle) can be found here.
The Open/Closed Principle, OCP in short, is credited to Bertrand Mayer, a French programmer, who first published it in his book Object-Oriented Software Construction in 1988. The principle rose in popularity in the early 2000s when it became one of the SOLID principles defined by Robert C. Martin in his book Agile Software Development, Principles, Patterns, and Practices and later republished in the C# version of the book Agile Principles, Patterns, and Practices in C#. What we are basically talking about here is to design our modules, classes and functions in a way that when a new functionality is needed, we should not modify our existing code but rather write new code that will be used by existing code.
They start with a look at OCP in the overall SOLID context and an example of an obvious violation of the principle. Some example code is provided showing a "Progress" class that's bound to at "File" implementation, not abstracted. They offer three different options for solving the issue:
- Take Advantage of the Dynamic Nature of PHP
- Use the Strategy Design Pattern
- Use the Template Method Design Pattern
Each of the above comes with example code and some with illustrations of the structure they create.