Is having an empty base class bad design?

后端 未结 4 806
耶瑟儿~
耶瑟儿~ 2021-01-12 10:24

I need a base class for my DTO classes which will be used in my generic interfaces.

But the DTO classes have nothing in common. They are just dumb classes containing

相关标签:
4条回答
  • 2021-01-12 10:55

    If they have nothing in common, what are you going to do with the instances you retrieve from your list?

    In any case, having the base class means that when (okay, if) you identify something they do need to have in common later on, you don't have to go back and refactor (re-base) everything. But I'd consider using an interface rather than a base class for this sort of thing in any case, as it doesn't sound like there's a strong need to reuse underlying implementation (as they have nothing in common yet!). It'll depend on what you think they may end up having in common later on.

    0 讨论(0)
  • 2021-01-12 11:06

    It is not a bad design, although somewhat uncommon. Think of it this way - there are at least two benefits while there are no drawbacks:

    • The base class serves as a filter for your interfaces so that you can't pass just any object to them - just your DTO objects. Marker interfaces could to this too.
    • When they eventually do get something in common, it will be easy to add it there and you won't have to refactor everything.
    0 讨论(0)
  • 2021-01-12 11:10

    In java this is called a Tag Interface. The link provides some good background on tag interfaces, their uses and issues.

    0 讨论(0)
  • 2021-01-12 11:12

    The .NET coding guidelines say that having an empty base class or interface (also called “tag” interface) is indeed bad style. The preferred style is to use an attribute instead to annotate classes of the same kind. There is also an FxCop rule to enforce this convention.

    However, I sometimes (in rare cases) use this idiom when a common base class is useful to denote a common hierarchy even if no common functionality exists. Attributes cannot be used for this.

    For example, in an interpreter for a programming language several methods return a special base class Value, i.e. something which has a value inside that programming language. Basically, this value can be everything from a number to a string (which, are special classes, not System.Int32 or System.String) to a composite object. I could also return System.Object but this would make the typing of my public interface weaker.

    Good, self-documenting code profits from the restricted interface.

    0 讨论(0)
提交回复
热议问题