Single Responsibility Principle (SRP)
The Single Responsibility Principle (SRP) states that a class should have only one reason to change, meaning it should have only one responsibility or job.
Explanation:
Each class in a software application should focus on a single part of
the functionality provided by the software. When a class handles
multiple responsibilities, changes in one part of its functionality might
affect other unrelated parts, increasing the risk of bugs and making the code
harder to maintain.
Why it's important:
- Improves code
readability and maintainability
- Encourages separation
of concerns
- Makes the
class easier to test
- Reduces the
risk of unintended side effects when modifying code
Bad Example (Violates SRP):
public class ReportManager
{
public void GenerateReport() { /* logic to
generate report */ }
public void SaveToDatabase() { /* logic to
save to DB */ }
public void SendEmail() { /* logic to send
report via email */ }
}
Good Example (Follows SRP):
public class ReportGenerator
{
public void GenerateReport() { /* generate
logic */ }
}
public class ReportSaver
{
public void SaveToDatabase() { /* save
logic */ }
}
public class EmailSender
{
public void SendEmail() { /* email logic
*/ }
}
Each
class now has one responsibility, and changes to one function (like
email formatting) do not affect report generation or database storage.
Comments
Post a Comment