Loading...
Page 1 of 3
I. Single Responsibility Principle
-
Each
software→ software module should have one & only one reason to change. -
Kind of like loose coupling.
- Offers a modular way to those which details are involved in a particular operation.
-
Well, responsibilities
is directly→ are directly proportional to testability.- Examples:
loggingpersistencevalidation
- Examples:
-
Keep classes small, focused, & testable.
II. Open / Closed Principle
- Software entities (classes, modules,
funcn→ functions, etc.) should be open for extension, but closed for modification. - Typical approaches to extension:
- Parameter-based extension ✔️
- Inheritance-based extension ✔️
- Composition/Injection extension ✔️
Page 2 of 3
(continued) Open / Closed Principle
- eg.
switch→ Switch case statements- ↓
- Factory
- ↓
- Return new classes
III. Liskov Substitution Principle
-
Subtypes must be substitutable for their base types.
-
Tell, don't ask.
- This can be done by avoiding if-checks and assigning these responsibilities to a different class.
-
Look for:
- Type checking
- Null checking
- NotImplementedException
IV. Interface Segregation Principle
- Clients should not be
forced to depend→ forced to depend on methods they do not use. - Avoid large interfaces because more dependencies mean:
- More coupling
- More difficult testing
Page 3 of 3
(continued) Interface Segregation Principle
- eg.
// Bad example
INotificationService
sendGmail()
sendText()
(X - violates ISP)
// Good example
IEmailNotificationService
ITextNotificationService
public interface INotificationService : IEmail, IText
- It also can be extended.
SOLID Principles Overview Diagram
flowchart TD
SRP[Single Responsibility] --> OCP[Open / Closed]
SRP --> ISP[Interface Segregation]
ISP -->|interfaces must be fully implemented| LSP[Liskov Substitution]
OCP -->|Add functionality by adding more classes| ISP
ISP -->|Details depend on interfaces| DIP[Dependency Inversion]
DIP -->|Change behaviour by passing in different dependencies| OCP
ISP -->|Promotes small cohesive types| SRP