Have you ever heard SOLID principles?
SOLID stands for:
- Single responsibility principle
- Open/closed principle
- Liskov substitution principle
- Interface segregation principle
- Dependency inversion principle
Easy to understand, easier to violate
Those principles are not difficult to understand when you initially study them, however stick to them in your daily job is not trivial at all. Let’s make an example on the first one – Single Responsibility Principle – the easiest and probably the most violated one.
Let’s imagine you have a function named calculateTotalPrice(..) and it’s long, I don’t know, let’s say 50 lines of code. Is the single responsibility principle respected?
Maybe yes, is doing one thing: calculate the total price of the cart. However when we look at the code we see something like that:
//15 lines to multiply price of the single product by ordered quantity
//10 to sum all the entries of the cart
//15 to apply discounts
//10 lines to apply taxes
Are you still convinced the method is following Single Responsibility Principle? Clearly not.
It does five things:
- Coordinate total price calculation by applying sequentially four operations
- Calculate single entry price
- Sum all entries price
- Apply discount
- Apply taxes
If one of those five things changes, we have to touch this method – clearly it has more than one responsibility.
It’s really easy violate them without even realising it.
“Functional is cool, but do you know OO” by Sandro Mancuso
We start by suggesting this talk by Sandro Mancuso.