Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Helper class(es) vs functional inheritance. Best practice

I have commands classes that implement ICommand { Execute } interface. Several commands have duplicate pieces of code. I have several options how to DRY:

  • Create static helper class(es) and move duplicate code there
  • Create commands inheritance with protected helper methods

What would you suggest and why?

ADDED Thank you everyone who replied, many answers were alike and useful!

like image 814
Andrew Florko Avatar asked Jun 17 '10 19:06

Andrew Florko


People also ask

Should helper functions be in a class?

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.

Are helper classes an Antipattern?

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".

Should helper methods be above or below?

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.

Why do we use helper classes?

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).


2 Answers

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.

like image 180
Thien Avatar answered Sep 19 '22 18:09

Thien


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).

like image 32
Igor Krivokon Avatar answered Sep 18 '22 18:09

Igor Krivokon