I have commands classes that implement ICommand { Execute } interface. Several commands have duplicate pieces of code. I have several options how to DRY:
What would you suggest and why?
ADDED Thank you everyone who replied, many answers were alike and useful!
In PHP you can either put the relevant functions into a nampespace or within a class (inside a namespace). It's up to you, there's no right or wrong approach.
asawyer pointed out a few links in the comments to that question: Helper classes is an anti-pattern. While those links go into detail how helperclasses collide with the well known principles of oop some things are still unclear to me. For example "Do not repeat yourself".
According to Clean Code you should order your methods from top to bottom, in the order they are called. So it reada like a poem.
In object-oriented programming, a helper class is used to assist in providing some functionality, which isn't the main goal of the application or class in which it is used. An instance of a helper class is called a helper object (for example, in the delegation pattern).
Instead of static classes another option is to put the common code in a new class and use dependency injection to inject the helper class into the commands. This also goes with the composition over inheritance notion as well.
It completely depends on the nature of your duplicated code.
What are the inputs / outputs of you helper functions? Do they operate on a logically related set of variables? Then - yes, you'd better create a base class with those variables as members, and related set of helper functions.
Otherwise, if the parameters in your helper functions are not coherent, you would implement those functions as static functions anyway, right? I don't see reasons to complicate things with inheritance in this case and I would do it just with helper functions (or, if your language doesn't treat functions as first class citizens, use static helper class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With