Tag: Open/Closed Principle (OCP)


  • Liskov Substitution Principle (LSP)

    Subtypes must be substitutable for their base types. Example: Consider a scenario with a base class Bird and a derived class Penguin. // Violation of LSP public class Bird { public void fly() { System.out.println(“Flying”); } } public class Penguin extends Bird { @Override public void fly() { throw new UnsupportedOperationException(“Penguins can’t fly”); } }…

  • Open/Closed Principle (OCP)

    Software entities should be open for extension but closed for modification. Example: Let’s say you have a class that calculates the area of different shapes. // Violation of OCP public class AreaCalculator { public double calculateArea(Object shape) { if (shape instanceof Circle) { Circle circle = (Circle) shape; return Math.PI * circle.getRadius() * circle.getRadius(); }…

  • Single Responsibility Principle (SRP)

    A class should have only one reason to change. Example: Consider a class that handles both user data and its formatting. This violates SRP. // Violation of SRP public class User { private String name; private String email; public User(String name, String email) { this.name = name; this.email = email; } // Responsibility 1: Managing…