Before we Move on to Design Patterns, It is vital to see the SOLID Principles, the First Acronym S - > Single Responsibility principle. Let's dive into the What, Why and How
What is SRP?
The Single Responsibility Principle (SRP) is a fundamental principle in software development and object-oriented design. It states that a class or module should have only one reason to change, meaning it should have a single responsibility.
Why SRP is needed?
SRP is needed for the below reasons
- Code maintainability
- Code reusability
- Easy Testability
- Flexibility and extensibility
- Reduced coupling
How SRP is implemented?
For this implementation, we will use Java as the programming Language
we will have three classes
- one without SRP
- SRP implemented
- how functionality separated
public class WithoutSingleResponsibility {
private String book;
private String author;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public void searchBook() {
}
}
Explanation:
In the Above class, we have the getters and setters for the author and Book, and the intention of the class is to deal with the book and author. But the problem arises with the search book method. It leads to problems when the author name and book are set. So search method is not part of this class, and it needs to be separated from this class.
public class WithSingleResponsibility {
private String book;
private String author;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
}
Explanation:
Now that we have removed the search book from this class, this is a classical example of SRP.
public class WithSingleResponsibilitySearchSeperated {
WithSingleResponsibility withSingleResponsibility;
public WithSingleResponsibilitySearchSeperated(WithSingleResponsibility withSingleResponsibility) {
this.withSingleResponsibility = withSingleResponsibility;
}
public void searchBook() {
withSingleResponsibility.getBook();
withSingleResponsibility.getAuthor();
}
}
Explanation
This is the Separated class, where we create an object of the SRP class and will use it according to the functionality
Top comments (0)