Tuesday, January 5, 2021

SOLID Principles

 Single Responsibility Principle

The class should have only one reason to change. Don't put functions in a single class that have different reasons to change like schema, business logic, UI design, calculations, validations, technology, storage mechanism, communication mechanism, underlying os, and many more. 

Don't Mix concerns in a single class.

But you have to define your own definition of concern or responsibility for your own system.

 Open Closed Principle

A class should be open for extension and closed for modification. like adding a new feature we have to recompile and redeploy old code with it too. Like If Statements, switch statements, enums, etc.

So, High-level code shouldn't know about the low-level details and neither the vice versa. They shouldn't know about each other's existence 

But please don't guess abstraction if you don't know to wait for the change to come and then make abstraction and refactor.

You can create abstractions for common known types like validations, database schema, UI, etc 

 Liskov Substitution Principle

The derived class could be used in place of the parent class without breaking the program. 

Covariance: You can't change the return type of the method 
Contravariance: you can change the parameter type of the method.

One subrule is you cannot return a new exception or put an extra check if you do that means It works with one type and throws exceptions for another type hence violating the LSP.

 Interface Segregation Principle

The client should not be forced to implement methods it's not using. That means there shouldn't be implemented exceptions or empty methods just to comply with the interface.

 Dependency Inversion Principle

High-level modules should not depend on low-level modules and vice versa but both should depend on abstraction; Abstractions should not depend on details.
That means
Business Logic shouldn't know how the database, logging, or emailing is working or neither should email know about business logic. Both should know each other about IEmailSernder or ILogger. 
And those interfaces shouldn't know how the concrete implementation is working.

whenever you see a new somewhere you got a tight coupling and we want loose coupling.

No comments:

Post a Comment