Single Responsibility Principle (SRP) is a software design principle, the main purpose is, a class, a method should have only one reason. An application consists of many classes and functions. And every method and class will done single task. Understanding and extends will be easy if we keep the class or method for single task.
Let’s look a code which didn’t implement SRP principle.
class Device {
constructor(name='', type='', model=''){
this.name = name;
this.type = type;
this.model = model;
}
rining(){
if(this.name && this.type && this.model){
console.log(`${this.type} Ringing & model is ${this.name} - ${this.model}`);
} else {
this.errorLogged("Missing");
}
return true;
}
errorLogged(message){
console.log(message);
return true;
}
}
const device = new Device("Nokia", "Mobile", "2600");
device.rining(); // Mobile Ringing & model is Nokia - 2600
This violates the SRP principle, because the error logger is not responsibility of the Device class. We didn’t fulfill the single task for the Device class. Device class should only have device related task. Our device class have also Error logger task which didn’t expected in this Device class.
So we can now write your code again which can fulfill the SRP principle.
class ErrorLogged{
static logged(message){
console.log(message);
return true;
}
}
class Device {
constructor(name='', type='', model=''){
this.name = name;
this.type = type;
this.model = model;
}
rining(){
if(this.name && this.type && this.model){
console.log(`${this.type} Ringing & model is ${this.name} - ${this.model}`);
} else {
ErrorLogged.logged("Missing");
}
return true;
}
}
const device = new Device("Samsung", "Mobile", "A30");
device.rining(); // Mobile Ringing & model is Samsung - A30
This full code GitHub link is given you can check this out. On the next article we will learn another principle of SOLID which is Open-Closed Principle.