Rule
Software entities (e.g., classes, modules, functions) should be open for extension but closed for modification.
Description
The Open/Closed Principle (OCP) encourages software entities to be open for extension, meaning new functionality can be added without changing the existing code. This is typically achieved using inheritance or interfaces. The goal is to prevent the modification of existing code, which helps prevent introducing bugs and breaking functionality.
Benefits
-
Encourages Reusability: You can extend functionality without modifying existing code.
-
Improves Maintainability: New requirements can be met by extending existing code, without the need to touch it.
-
Prevents Bugs: By not modifying existing code, you reduce the risk of introducing bugs.
Example (Correct):
interface Shape {
public function area();
}
class Circle implements Shape {
public function area() {
// Calculate circle area
}
}
class Square implements Shape {
public function area() {
// Calculate square area
}
}
Example (Incorrect):
class AreaCalculator {
public function calculateArea($shape) {
if ($shape instanceof Circle) {
// Calculate circle area
} elseif ($shape instanceof Square) {
// Calculate square area
}
}
}