The Open/Closed Principle (OCP) is the second SOLID principle and states that a software entity, such as a class or module, must be open for extension but closed for modification. This means that an entity's behavior must be extended without changing its existing source code. In other words, new features can be added without modifying existing code. To achieve this, OCP encourages the use of interfaces, abstract classes, and design patterns that allow the addition of new functionality without the need to change existing code.
Example Before Applying OCP in PHP:
<?php
class Calculator {
public function calculate($operation, $a, $b) {
switch ($operation) {
case 'sum':
return $a + $b;
case 'subtract':
return $a - $b;
// other operations...
}
}
}
In this example, the Calculator
class has a calculate method that performs several operations, but the code needs to be modified whenever a new operation is added. This violates the OCP principle as the class is closed for extension (not easy to add new operations) and open for modification (you need to modify the class to add new operations).
Example After Applying OCP in PHP:
<?php
abstract class Operation
{
abstract public function calculate($a, $b);
}
class Sum extends Operacao
{
public function calculate($a, $b)
{
return $a + $b;
}
}
class Subtraction extends Operacao
{
public function calculate($a, $b)
{
return $a - $b;
}
}
class Calculator
{
public function calculate(Operation $operation, $a, $b)
{
return $operation->calculate($a, $b);
}
}
In this example, the Operation
class was transformed into an abstract class, keeping the calculate method as abstract. The Sum and Subtraction classes now extend the Operation
abstract class and implement the calculate
method, as needed for each specific operation. The Calculator
class remains unchanged and accepts objects from classes that derive from Operation. This design allows you to add new operations by creating new classes that extend Operation
, without the need to modify the Calculator class. Thus, the OCP principle is respected, as the Calculator class is open for extension and closed for modification.
Thanks for reading!
If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!
😊😊 See you later! 😊😊
Support Me
Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso
Top comments (0)