Base class vs Utility class

与世无争的帅哥 提交于 2019-12-05 04:38:30

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!