开发者

Base class vs Utility class

Which of the two should be preferred?

There are some methods which are called by class A, B and C.

Should those methods be encapsulated in a class D (base of A, B 开发者_JAVA百科and C) ?

OR

Should those methods be encapsulated in a class U and other classes creats it's object to use the methods as required.

On what basis decision should be taken?

Thanks.


You should make a static utility class.

Only use inheritance if it's actually meaningful—if A, B, and C actually are a D.


I'd base the decision on what the methods are doing, if they're doing things specific to classes A, B and C then they should be in the base class. This helps keep code clean, by hiding class-related functionality away from the rest of the system. (of course, I'm assuming that A, B and C either already inherit from D, or are obviously related)

If they're doing things with other types, that aren't inherent in what A, B and C do, then in order to maximise opportunities for reuse they should be in a utility class.

If they're doing things with other types that are specific to that other type (e.g. pretty-printing a datetime) consider making them extension methods for that type.


I would tend away from inheritance unless there's an obvious is-a relationship. I suspect from your description above that this is not the case. My preferred solutions would be:

  1. inject an instance of a utility class into your A, B, C
  2. have A, B, C instantiate the appropriate utility classes

The advantage of injecting the class is that you can provide different implementations trivially. This is especially useful for testing. Singletons or classes with static methods tend to cause problems for the same reason - you can't easily override or substitute them.


Use 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 that case your derived class should be completely substitutable for your base class. There should not be any switch logic to check the derived type and act accordingly. See Liskov Substitution Principle: http://en.wikipedia.org/wiki/Liskov_substitution_principle

Use Utility Class Some languages have the limitation that they do not support multiple inheritance. If you already have a meaningful base class then you need to go for the utility class. Also, when you are using inheritance your are creating tight coupling between from the dervied class to the base class.

I would go for base class if the derived class is naturally substitutable for its base class. If the purpose is just to share some reusable code between classes, then it makes more sense to go with utility class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜