Sobes.tech
Junior — Middle

How to implement SOLID principles in real projects?

sobes.tech AI

Answer from AI

The SOLID principles help write maintainable and extendable code. In real projects, they can be implemented as follows:

  • Single Responsibility Principle (SRP): Each class or module is responsible for a specific task. For example, a class responsible for database operations should not handle display logic.

  • Open/Closed Principle (OCP): Classes should be open for extension but closed for modification. This is achieved through the use of abstractions and inheritance. For example, when adding new functionality, create a new class implementing an interface instead of modifying existing code.

  • Liskov Substitution Principle (LSP): Subclasses should be interchangeable with their base classes without breaking the logic. This means that subclass methods should not alter the expected behavior.

  • Interface Segregation Principle (ISP): It is better to have several specialized interfaces than one general interface. Clients should not depend on methods they do not use.

  • Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules directly; both should depend on abstractions. For example, using dependency injection through interfaces.

Example of implementing DIP in Java:

interface NotificationService {
    void send(String message);
}

class EmailNotification implements NotificationService {
    public void send(String message) {
        // send email
    }
}

class UserController {
    private NotificationService notificationService;

    public UserController(NotificationService notificationService) {
        this.notificationService = notificationService;
    }

    public void notifyUser() {
        notificationService.send("Hello user!");
    }
}

Thus, it is easy to replace EmailNotification with another notification type without changing UserController.

How to implement SOLID principles in real projects… - sobes.tech