Friday, August 13, 2021

SOLID

 A programmer who goes fast rapidly now is guaranteed to go slow in the future Uncle Bob 

How do you identify bad code? 

Rigidity, When you modify something and it breaks something else. Now you have to modify something else to make it consistent.

Fragility: breaks other parts when you change one part and have no relationship to each other.

Coupled Code, 


Inheritance

Encapsulation

Polymorphism

Abstraction


Anticipating change is a bad idea so the best predictor of change is paste change.

Single Responsibility Principle

The class should have only reason to change or responsibility. Don't put functions in a single class that has 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 be emailing 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