01. What is SOLID?


01. What is SOLID?




What is SOLID?

SOLID is a set of  five design principles in object-oriented programming that make your code cleaner, modular, flexible, and maintainable

S – Single Responsibility Principle (SRP)

O – Open/Closed Principle (OCP)

L – Liskov Substitution Principle (LSP)

I – Interface Segregation Principle (ISP)

D – Dependency Inversion Principle (DIP)


1. Single Responsibility Principle (SRP)

 A class, ethos or veritable should responsible to handle only one thing (have only one reason to change).

Bad:

class Report {
void generateReport() {}
void saveToFile() {}
}


Good:

class ReportGenerator {
void generate() {}
}

class ReportSaver {
void saveToFile() {}
}


2. Open/Closed Principle (OCP)

Software entities should be open for extension but closed for modification.

 Bad:

class Payment {
void process(String type) {
if (type.equals("credit")) {}
else if (type.equals("paypal")) {}
}
}

Good:

interface PaymentMethod {
void process();
}

class CreditCard implements PaymentMethod {
public void process() {}
}

class PayPal implements PaymentMethod {
public void process() {}
}

class PaymentProcessor {
void pay(PaymentMethod method) {
method.process();
}
}


3. Liskov Substitution Principle (LSP)

Subtypes must be replaceable for their base types without breaking behavior.

Violates LSP:

class Bird {
void fly() {}
}

class Ostrich extends Bird {
void fly() { throw new UnsupportedOperationException(); }
}

Fix:

class Bird {}

class FlyingBird extends Bird {
void fly() {}
}
class Ostrich extends Bird {} // no fly method


4.  Interface Segregation Principle (ISP)

Don’t force a class to implement methods it doesn’t use.

Bad:

interface Worker {
void work();
void eat();
}

class Robot implements Worker {
public void work() {}
public void eat() {} // not applicable
}

Good:

interface Workable {
void work();
}

interface Eatable {
void eat();
}

class Robot implements Workable {
public void work() {}
}


 5. Dependency Inversion Principle (DIP)

High-level modules should not depend on low-level modules.

Both should depend on abstractions.

Bad:

class MySQLDatabase {
void connect() {}
}

class App {
MySQLDatabase db = new MySQLDatabase();
void start() {
db.connect();
}
}


Good:

interface Database {
void connect();
}

class MySQLDatabase implements Database {
public void connect() {}
}

class App {
Database db;
App(Database db) {
this.db = db;
}

void start() {
db.connect();
}
}

Comments

Popular posts from this blog

Database - Topics

02. Spring – Creating spring project clone it with GIT step by step.

01. Steps in SQL Query Execution (MySQL)