SOLID - Single Responsibility, Open/Closed Principle

Publish date: 2024-06-25
Tags: System-Design, Software-Engineering

Single Responsibility Principle

SRP

Case study - Design a bird

SRP

public class Bird {
	private int weight;
	private String colour;
	private String type;
	private String size;
	private String beakType;
	
	public void fly() {
		...
	}
	
	public void eat() {
		...
	}
	
	public void makeSound() {
		...
	}
}
public void fly() {
	if (type.equals("eagle")) {
		flyLikeEagle();
	} else if (type.equals("penguin")) {
		flyLikePenguin();
	} else if (type.equals("parrot")) {
		flyLikeParrot();
	}
}

Reasons to follow SRP

How/Where to spot violations of SRP

public saveToDatabase() { 
	// Connect to database 
	// Create a query 
	// Execute the query
	// Create a user defined object 
	// Close the connection
}

Open/Closed Principle

public void fly() {
	if (type.equals("eagle")) {
		flyLikeEagle();
	} else if (type.equals("penguin")) {
		flyLikePenguin();
	} else if (type.equals("parrot")) {
		flyLikeParrot();
	}
}

Abstract classes and interfaces

When to use abstract classes and interfaces?

Fixing OCP violation in the Bird class

SRP

These are my notes from the Low-Level Design (LLD) course I took at Scaler.

Check Python, Java and Go code on Github Repo

Tags: System-Design, Software-Engineering