Junior — Middle
Can you give an example of a situation where the open/closed principle is violated?
sobes.tech AI
Answer from AI
The Open/Closed Principle states that software entities should be open for extension but closed for modification. Violations occur when adding new functionality requires changing existing code.
Example of violation:
Suppose there is a class that calculates delivery cost for different types of products, and to add a new product type, you need to change the method with conditional statements:
class DeliveryCalculator {
public double calculatePrice(String productType) {
if (productType.equals("Book")) {
return 5.0;
} else if (productType.equals("Electronics")) {
return 10.0;
}
// To add a new product type, this method must be changed
else if (productType.equals("Furniture")) {
return 20.0;
}
return 0;
}
}
Here, adding a new product type requires modifying the calculatePrice method, which violates the open/closed principle. A better approach would be to use polymorphism, for example, create a Product interface with a getDeliveryPrice() method, and implement this interface for each product type.