mardi 5 février 2019

Single Responsibility Principle without code duplication (how to do?)

I address this question to people with advanced knowledge in the field of software architecture. I am trying to understanding the idea of Single Responsibility Principle (SOLID) related to the idea of elimination of code redundancy. My perception of code duplication was that code duplication is something wrong that needs to be fixed and eliminated. Actually I am reading the “Clean Architecture” (Robert C. Martin) and my perception changed and I am a little confused.

The SRP emphasizes the actor, so Robert Martin writes “A module should be responsible to one, and only one, actor”. As an example R. Martin talks about two classes (modules). The first class contains the method “calculatedPay()” specified by the accounting deparament. The other class contains the method “reportHours()” specified by another actor, the human resource department. Both functions share common algorithm (for example something like hour calculation). The natural approach would be to move the common algorithm to another class and eliminate the code duplication. After that both functions would call the algorithm in the new class. Imagine the accounting department needs to change the algorithm (in the new class). After the change the human resource department uses a new (invalid) algorithm. There is a problem and the problem is caused by breaking the SRP. The algorithm class (module) is responsible to two actor. On the other hand, we have unnecessary code duplication, which makes me restless.

Maybe my dogmatic approach about code duplication is wrong, and there is nothing wrong to have the same code in many places. Isn't it? If I look at it from a different perspective, then I see there are multiple algorithms / or just code parts used by multiple clients (actors). And sometimes the used code needs to be change. It is something naturally for me. What would be the another way? That’s why I do not quite understand why not to place the duplication into another class. Another example with a different view, two classes with one function each, sharing common algorithm but both specified by the accounting department. There is no SRP break, because there is only one actor by the same problem still exists. This is somehow very inaccurate...

Maybe I don’t understand the SRP and the idea behind...

Aucun commentaire:

Enregistrer un commentaire