What is SOLID? Provide examples of principles.
sobes.tech AI
Answer from AI
SOLID is a set of five principles of object-oriented programming aimed at improving the structure and maintainability of code:
-
S — Single Responsibility Principle: a class should have only one reason to change, meaning it should be responsible for a single task.
-
O — Open/Closed Principle: software entities should be open for extension but closed for modification.
-
L — Liskov Substitution Principle: objects of a subclass should be interchangeable with objects of the superclass without affecting the correctness of the program.
-
I — Interface Segregation Principle: clients should not depend on interfaces they do not use.
-
D — Dependency Inversion Principle: high-level modules should not depend on low-level modules; both should depend on abstractions.
Example for Single Responsibility Principle:
class Report {
public String generateReport() {
// report generation logic
}
}
class ReportPrinter {
public void print(String report) {
// report printing logic
}
}
Here, report generation and printing are separated into different classes, each responsible for its own task.