Reputation: 109
I have a class 'A' which is almost perfect for my needs. Class 'B' uses class 'A'
I've now designed Class 'C' and Class 'D' and noticed that there is a good chunk of code in class 'B', 'C' and 'D' for using Class 'A' is duplicated. I've separated out this code in specific, standalone functions in each of the classes.
Now I'm wondering where this code should go. At the moment, the functions are duplicated in the three calling classes (B, C and D).
Placing the functions into class 'A' would break the single responsibility principle. Inheritance to add functionality would likely break both SRP and LSP.
The one that seems that it may work is composition.
Q: Is designing a complete class just for a few functions over kill?
Q: Would it be valid for classes 'B', 'C' and 'D' to access both the new class 'E' (which would depend on A) and the old class 'A' (which would have to be the same instance as the instance in the new class 'E'), or should the new class 'E' provide sufficient functionality so that Classes B, C and D don't need to access Class A directly? It would seem that its then an incomplete interface with additional functionality.
Or should the new class 'E' do something and return the result to class B, C, D, which they can then pass on to class 'A' themselves. Actually, no, that can't work as the class would have to called again on certain return values.
Or should I do it a completely different way?
(and why does software design require so much thinking?)
An example usage scenario:
Class B: while ((A->DoSomething() == ERROR/TIMEOUT/etc) && (retries < 3)) { retries ++; A->SetSomeParameters(); }
(actual code is larger)
Upvotes: 1
Views: 212
Reputation: 11831
If the code so duplicated is (a) large(ish), (b) will probably change in lockstep to all using classes, and thus (c) runs the risk of drifting apart creating new bugs, I'd go for creating a (hidden) class containing that functionality and inherit it as needed.
In any case, consider carefully costs vs benefits. Adding one version of the function(s) creates rigidity which might need to be removed (splitting up again) later on. "Do work now, it might be useful later on" more often than not turns out to just create extra work for later (Murphy's law being absolutely relentless). The overall architecture is more important than details of possible duplications.
Upvotes: 0