SOLID
SOLID
S — Single Responsibility
A class should have a single responsibility
Goal
Thisprinciple aims to separate behaviours so that if
bugs arise as a result of your change, it won’t affect
other unrelated behaviours.
IMPLIMENTATION :
// After SRP
class Call {
void makeCall() { /* ... */ }
}
class Camera {
void takePhoto() { /* ... */ }
}
class MusicPlayer {
void playMusic() { /* ... */ }
}
O — Open-Closed
Classes should be open for extension, but closed for
modification
Goal
This principle aims to extend a Class’s behaviour without
changing the existing behaviour of that Class. This is to
avoid causing bugs wherever the Class is being used.
Example
class Circle {
double radius;
double area() {
return Math.PI * radius * radius;
}
}
// After OCP
interface Shape {
double area();
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
@Override
public double area() {
return width * height;
}
}
L — Liskov Substitution
If S is a subtype of T, then objects of type T in a program
may be replaced with objects of type S without altering
any of the desirable properties of that program.
When a child Class cannot perform the same actions as
its parent Class, this can cause bugs.
Goal
This principle aims to enforce consistency so that the parent
Class or its child Class can be used in the same way without
any errors.
Example
// After ISP
interface Sender {
void send();
}
interface Receiver {
void receive();
}
interface Displayable {
void display();
D — Dependency Inversion
- High-level modules should not depend on low-level
modules. Both should depend on the abstraction.
- Abstractions should not depend on details. Details should
depend on abstractions.
Goal
This principle aims at reducing the dependency of a high-level
Class on the low-level Class by introducing an interface.
// Before DIP
class MusicPlayer {
void playMP3() { /* ... */ }
}
class AudioApp {
private MusicPlayer musicPlayer = new MusicPlayer();
void playAudio() {
musicPlayer.playMP3();
}
}
// After DIP
interface AudioPlayer {
void play();
}
class AudioApp {
private AudioPlayer audioPlayer;
AudioApp(AudioPlayer audioPlayer) {
this.audioPlayer = audioPlayer;
}
void playAudio() {
audioPlayer.play();
}
}
SOLID principles | Advantages