Base class vs Utility class

Which of the two should be preferred?

There are several methods that are called by classes A, B, and C.

Should these methods be encapsulated in class D (base A, B, and C)?

OR

If these methods need to be encapsulated in class U and other types of classes, they do not want to use methods as needed.

On what basis should a decision be made?

Thanks.

+5
source share
4 answers

You must make the utility class static .

Use only inheritance if it is really meaningful - if A , B and C are actually D

+9
source

I would base a decision on what methods do, if they do things specific to classes A, B and C, then they should be in the base class. This helps keep the code clean by hiding the functionality associated with the class from the rest of the system. (of course, I assume that A, B and C are either already inherited from D, or are explicitly related)

If they do things with other types that are not inherent in what A, B and C do, then in order to maximize the possibilities for reuse, they should be in the utility class.

If they do something with other types specific to this other type (for example, pretty-type datetime), consider making them extension methods for that type.

+3
source

I would shy away from inheritance if there was no obvious is-a relationship. I suspect that from the above description this is not the case. My preferred solutions:

  • insert the utility class instance into your A, B, C
  • have A, B, C, create the corresponding utility classes

The advantage of class input is that you can implement various implementations trivially. This is especially useful for testing. Singletones or classes with static methods tend to cause problems for the same reason - you cannot easily override or replace them.

+2
source

Use a base class If you are going to write some logic only depending on the base class, then it makes sense to create a base class. In this case, your derived class should be completely replaced for your base class. There should be no switch logic to verify the derived type and actions accordingly. See Liskov replacement principle: http://en.wikipedia.org/wiki/Liskov_substitution_principle

Use the Utility class Some languages ​​have the limitation that they do not support multiple inheritance. If you already have a meaningful base class, you need to go to the utility class. In addition, when you use inheritance, you create a hard link between the dervied class and the base class.

I would go for a base class if the derived class naturally replaces its base class. If the goal is to split some reusable code between classes, then it makes sense to go with the utility class.

0
source

All Articles