Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does SRP in SOLID principle lead to Lasagna Code?

With SOLID principle especially SRP, we have so very many classes..
I mean, it's just like you want to build a database class
Then, you have
DatabaseHandler class which handle the database (select,insert,update,delete,etc),

DatabaseAdapter class which is an extended PDO class (may set the prefered default mode in construction, a new prepare method which directly prepare the statement, bind it with the param, and execute it,

QueryBuilder Class which is the parent of SelectStatementBuilder Class, InsertStatementBuilder Class, DeleteStatementBuilder Class, UpdateStatementBuilder Class (to build SQLStatement),

Expression Class which builds up expression needed in WHERE clause

SQLStatement Class (which acts just like a normal string but its interface is SQLStatementInterface so we can know that it's a SQL Statement etc..

And, I know there will be more classes if I dig it deeper down, and refactor again.

Does SRP principle implementation lead to Lasagna code ? Is Lasagna code alright ?

like image 863
Terry Djony Avatar asked May 03 '15 05:05

Terry Djony


1 Answers

In general, SRP is a design principle that requires you to think through the different responsibilities (AKA reasons to change) of your system. Its goal is to help improve your system cohesion. In other words, things that change together, stay together.

Uncle Bob defined SRP as:

A class should have only one reason to change.

When taken at the wrong level of granularity, SRP can be interpreted as a class should only do one very small, low-level thing, leading to over-abstraction with no clear benefits. Reading through his paper, you will notice that the "reason to change" is defined at the user/client/consumer requirement level. A simplistic example is that if a change in my UI requirement causes me to change a class that contains some data access layer codes, then the class has more than one reasons to change (i.e. UI and data access) which violates the SRP.

In your case, unless you are building a database management tool, there are no reasons to break the original database class into these many smaller classes. If this is a typical (web) application, then if you wanted to change the underlying database implementation (say from MySQL to in-memory database during testing), then all these classes will have to be replaced anyway. Might as well just keep it simple.

like image 66
ivan.sim Avatar answered Sep 24 '22 02:09

ivan.sim