SOLID New Flashcards
What does the Single Responsibility Principle state?
A class, module, or method should have only one reason to change and should focus on a single functionality.
What are common signs of a Single Responsibility Principle (SRP) violation?
A class serves more than one actor, has responsibilities for multiple functionalities, or contains entangled methods that serve different purposes.
What are the problems caused by SRP violations?
Classes become tightly coupled, changes in one part can affect the entire system, and they can lead to ‘God classes’ that know or do too much.
What is an example of SRP violation?
A class like DLModel
that includes preprocess
, train
, and evaluate
methods serving three different functionalities.
How can you improve SRP violations in the DLModel example?
Separate the functionalities into individual classes: Preprocessor
for preprocess
, DLModel
for train
, and Evaluator
for evaluate
.
What does the Open/Closed Principle state?
Software entities (classes, modules, methods, etc.) should be open for extension but closed for modification.
What is a common sign of an Open/Closed Principle violation?
Classes containing switch
or if
statements that require modification when adding new functionality.
What is the benefit of adhering to the Open/Closed Principle?
You can extend functionality without altering existing code, making the codebase more stable and maintainable.
What does the Liskov Substitution Principle (LSP) state?
Objects of a superclass should be replaceable with objects of a subclass without altering the correctness of the program.
What is an example of an LSP violation?
A Square
class inherits from a Rectangle
class but violates the ‘is-a’ relationship due to differences in how they calculate area (e.g., width × height vs. side × side).
How can LSP violations be fixed in the Rectangle-Square example?
Create a Shape
abstract class with a calculate_area
method and let Rectangle
and Square
extend this class, implementing their specific logic.
What does the Interface Segregation Principle state?
Clients (classes and subclasses) should not depend on methods they do not use. It’s better to have many specific interfaces than a single general one.
What is an example of an Interface Segregation Principle violation?
An OldPrinter
class inherits from a Printer
interface with methods like print
, scan
, and fax
, but OldPrinter
does not need scan
and fax
.
How can ISP violations be fixed in the Printer example?
Create smaller interfaces like Print
, Scan
, and Fax
, and let OldPrinter
implement only the Print
interface while NewPrinter
implements all three as needed.
What does the Dependency Inversion Principle (DIP) state?
Abstractions should not depend upon details; details should depend upon abstractions.