High-level modules should not depend on low-level modules. Both should depend on abstractions. Example: Consider a Light class that directly controls a Switch. // Violation of DIP public class LightSwitch { private Light light; public LightSwitch(Light light) { this.light = light; } public void turnOn() { light.turnOn(); } public void turnOff() { light.turnOff(); } }…
Clients should not be obligated to rely on interfaces they don’t utilize. Example: Consider an interface that imposes irrelevant methods on implementing classes. // Violation of ISP public interface Worker { void work(); void eat(); } public class HumanWorker implements Worker { public void work() { System.out.println(“Human working”); } public void eat() { System.out.println(“Human eating”);…
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”); } }…
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(); }…
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…
The SOLID design principles in Java are a set of guidelines that help developers create robust, scalable, and maintainable software. These principles are foundational in object-oriented programming and play a critical role in ensuring that your codebase remains flexible and adaptable as it evolves. Let’s break down what SOLID means and why it’s essential: 1.…