Sobes.tech
Junior — Middle

Can you give an example of applying the Single Responsibility Principle (D from SOLID) in your projects?

sobes.tech AI

Answer from AI

The Single Responsibility Principle (SRP) from SOLID states that a class should have only one reason to change, meaning it should be responsible for a single specific task.

In my projects, I applied this principle by dividing logic into separate classes. For example, in an order processing project:

  • The Order class is responsible only for order data (items, quantity, cost).
  • The OrderValidator class handles order validation.
  • The OrderRepository class is responsible for saving the order to the database.
  • The OrderNotifier class handles sending notifications to the customer.

This separation makes maintenance and testing easier, as changes in validation logic do not affect saving or notification processes.

Here's an example in C#:

public class Order
{
    public int Id { get; set; }
    public List<Item> Items { get; set; }
}

public class OrderValidator
{
    public bool Validate(Order order)
    {
        // Order validation
        return order.Items != null && order.Items.Count > 0;
    }
}

public class OrderRepository
{
    public void Save(Order order)
    {
        // Save to database
    }
}

public class OrderNotifier
{
    public void Notify(Order order)
    {
        // Send notification
    }
}

This approach complies with SRP and improves code structure.

Can you give an example of applying the Single… - sobes.tech