SOLID principles
Solid principles are basically coding standards and they were promoted by Robert C.Martin also known as Uncle Bob. SOLID principles all together helps developers to avoid frailer in designs. When building a software, we should use SOLID principles to avoid bad designs and increase the code quality.
SOLID principles
- S – Single responsibility principle
- O- Open closed principle
- L- Liskov substitution principle
- I- Interface segregation principle
- D- Dependency inversion principle
In this article lets look at the single responsibility principle.
So what is really single responsibility is …
Single responsibility principle is the class has only one reason to change.it has only one responsibility but it doesn’t mean that it only has one method. It can have more than one method, but the all methods should directly relate to the responsibility of the class. Single responsibility is that the class only do one thing.
Lets look at an example
class invoice {
public void details (){
}
public double calculateTax(){
}
public void emailInvoice(){
}
}
This example may seem okay, but it violates the single responsibility principle in many ways. A class should only have a single responsibility and when you describe the class if you use the word “and” the class may need to be refactored. Let’s look at an example
“the invoice class can print invoice details “and” calculate taxes “and” send emails”
So basically, this class has multiple responsibilities “print invoice details, calculate taxes and send emails “
So lets take the activates between “and” and then make them into independent classes and the best example is the taxes class because it usually required by other classes other than invoice class.
Class taxes {
Public void calculateTax(){
}
}
This way the tax class can be used by any other classes or independently. That means anyone can work on tax class without having to work on invoice class. that is called law coupling as well.
And same as tax class other classes also should be refactored as single classes to achieve the single responsibility principle
I hope this article helps you to understand the single responsibility principle and see you again with another exciting article