SOLID Flashcards
What are the names of the 5 SOLID principles?
Single Responsibility
OPEN/CLOSED
Liskov Substitution
Interface Segregation
Dependency Inversion
What is single responsibility?
A class should have one and only one reason to change, meaning that a class should have only one job. This means that a class should be extendable without modifying the class itself
What is an issue with not following this principle?
Changes in one area can inadvertently affect other unrelated areas, a tightly coupled system that is hard to maintain.
Example of Single Responsibility?
Report class has both a generateReport and sendReportByEmail methods. Now modifying the way reports are generated could unintentionally affect the email functionality
public class Report {
public void generateReport()
public void sendReportByEmail(String emailAddress)
}
What is OPEN/CLOSED
Objects or entities should be open for extension but closed for modification
What is an issue with not following this principle?
Modifying existing code can potentially cause new bugs in an otherwise happy application
What is an exception to OPEN/CLOSED?
Fixing a bug in the existing code
How does the Single Responsibility principle help us build better software?
Testing – A class with one responsibility will have far fewer test cases.
Lower coupling – Less functionality in a single class will have fewer dependencies.
Organization – Smaller, well-organized classes are easier to search than monolithic ones.
What is the Liskov Substitution?
If class A is a subtype of class B, we should be able to replace B with A without disrupting the behavior of our program.
Example:
A Bird class with method of fly(). Introducing a sparrow and eagle subclass works fine but a penguin introduces a problem. To fix this we could introduce a more appropriate design such as separating flying and non-flying birds with an interface flyable so now a sparrow is a subclass of bird but implements flyable while a penguin does not.