SRP can also be applied at the method level. A method should perform a single task. If a method does more than one task, it should be split into smaller methods.
public class UserService
{
public void RegisterUser(string username, string password)
{
// Validate user
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
{
throw new ArgumentException("Username and password are required.");
}
// Save user to database
var user = new User { Username = username, Password = password };
SaveUserToDatabase(user);
// Send confirmation email
SendConfirmationEmail(user);
}
private void SaveUserToDatabase(User user)
{
// Logic to save user to the database
}
private void SendConfirmationEmail(User user)
{
// Logic to send confirmation email
}
}
In this example, the RegisterUser method has multiple responsibilities: validation, saving to the database, and sending an email.
We can refactor this method into smaller methods, each with a single responsibility.
public class UserService
{
public void RegisterUser(string username, string password)
{
ValidateUser(username, password);
var user = CreateUser(username, password);
SaveUser(user);
SendConfirmationEmail(user);
}
private void ValidateUser(string username, string password)
{
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
{
throw new ArgumentException("Username and password are required.");
}
}
private User CreateUser(string username, string password)
{
return new User { Username = username, Password = password };
}
private void SaveUser(User user)
{
// Logic to save user to the database
}
private void SendConfirmationEmail(User user)
{
// Logic to send confirmation email
}
}
Now, each method has a single responsibility, adhering to the SRP.