Principle#1(SRP)

Principle#1: The single responsibility Principle.

“A class should have one, and only one, reason to change.”Defined by Robert C. Martin in his book Agile Software Development, Principles.

This principle states that if we have 2 reasons to change for a class, we have to split the functionality in two classes. Each class will handle only one responsibility and on future if we need to make one change we are going to make it in the class which handle it. When we need to make a change in a class having more responsibilities the change might affect the other functionality of the classes.

As per SRP, there should not be more than one reason for a class to change, or a class should always handle single functionality. If you put more than one functionality in one Class in C# it introduce coupling between two functionality and even if you change one functionality there is chance you broke coupled functionality, which require another round of testing to avoid any surprise on production environment.

Let’s look at below example to understand it better.

public class TicketReservation
    {
        public void OnlineReservations(ReservationDetails reservation)
        {
            // business logic, validation, etc…
            // save booking to database
            new OnlineReservationDB().Save(TicketReservation);
        }
    }

This class has clearly just one responsibility and it doesn’t violate the SRP as its only responsibility now is to validate data and call a data access layer to persist the online reservation data. Since it only has one responsibility, it also has only one reason to change.

Posted in OOD

Leave a comment