The Single Responsibility Principle (SRP), also known as the Singularity Principle, is a software design principle that states that a class should have only one reason to change.
That is, by Single Responsibility Principle each class should have only one responsibility, and that responsibility should be entirely encapsulated by the class.
The Singularity Principle is one of the SOLID principles of object-oriented design, which are a set of guidelines for creating maintainable and scalable software systems.
To illustrate the Singularity Principle in C#, consider the following example,
public class Customer
{
public string Name { get; set; }
public string Address { get; set; }
public bool IsValid()
{
// Check if the customer's information is valid
// ...
}
public void Save()
{
// Save the customer's information to the database
// ...
}
}
In this example, the Customer class has two responsibilities: validating customer information and saving customer information to the database. This violates the Singularity Principle, as there are two reasons why the Customer class might need to change: if the validation rules change, or if the database schema changes.
To apply the Singularity Principle, we can separate the two responsibilities into separate classes:
public class CustomerValidator
{
public bool IsValid(Customer customer)
{
// Check if the customer's information is valid
// ...
}
}
public class CustomerRepository
{
public void Save(Customer customer)
{
// Save the customer's information to the database
// ...
}
}
In this revised example, the CustomerValidator class is responsible for validating customer information, and the CustomerRepository class is responsible for saving customer information to the database.
This adheres to the Singularity Principle, as each class has only one responsibility, and that responsibility is entirely encapsulated by the class.
Now, if the validation rules change, we only need to modify the CustomerValidatorclass, and if the database schema changes, we only need to modify the CustomerRepository class.
This makes our code more maintainable and scalable over time.
Leave a Reply