SOLID Architecture

I think it’s appropriate to consider a few things before we talk about Single Responsibility Principals and that is why the SOLID principle exists. The SOLID Principles are the framework of designing the code in a way that allows for a code base to grow without unnecessarily introducing bugs into the code. If you choose to follow my blog series “Solid Principles” we will cover each of the principles and give the reader a better grasp on what they are and why we use them.

 

Single Responsibility Principle

The Single Responsibility Principle, or SRP, is the first of five SOLID Architectural principles used in object-oriented coding. The other 4 are:

Open-Closed

Liskov Substitution

Interface Segregation

Dependency Inversion

 While it is possible to design and write a program in a single class and possibly be fine there are many problems that will become increasingly apparent as the code base grows. As the code becomes larger it can become cumbersome to find specific lines of code, or make unique variable names, but often the first of many problems. What happens when the company decides to split up tasks and give them to different teams. It would become very difficult and slow to blend that code together in a single class as the class grows. Also, what happens when the company decides they want to hire a new developer? Suddenly they have the daunting task of learning the company’s entire code base and how they avoid unwanted bugs that really should have to be there in the first place. This is where the birth of Single Responsibility comes in. We design our code to be loosely coupled in a way that allows portions of our code to have a single main purpose. Handling the code this way will allow only the essential information to be passed into that class and return, if at all, only the essential information back. Keeping the focus of a class minimal allows code to be reused in other parts of our code, specially making our code more modular.

Think of it like this: When I go to the grocery store to buy food, I don’t care how the food gets there and it isn’t my responsibility to follow the money after I pay for the food. My single goal was to get plugged into the store, get passed some food and pass the store money in return. This is how we build our website. A single goal in mind.

 

// i have $20 on my card and pay at the register. bread is $5. 
double cardMoney = 20.00;
double breadCost = 5.00;

//Call method from another class
cardMoney = BillCustomer(cardMoney, breadCost);

 

In another code block:

public static BillCustomer(double cardMoney, double breadCost)
{
   return cardMoney - breadCost;
}

 

These have two separate purposes and it might be easy to see how we could actualy change those values pretty easily without making changes to the other portion of our code. These are loosely coupled and have single responisbilities assigned to them.