Interface + Extension (mixin) vs Base Class

后端 未结 3 1601
忘掉有多难
忘掉有多难 2021-01-30 09:28

Is an interface + extension methods (mixin) preferable to an abstract class?

If your answer is \"it depends\", what does it depend upon?

I see t

3条回答
  •  没有蜡笔的小新
    2021-01-30 10:03

    IMHO, this is the wrong question.

    You should use everything for what it is designed for.

    • Extension methods are not members. They are syntactically looking like members, so you can find them easier.
    • Extension methods can only use the public (or internal) interface. Many other classes could do the same. So extension methods are not a real encapsulation in an oo way.
    • They are static methods and can not be overridden and not be mocked in a unit test. Is is a non-OO language feature and the caller is statically bound to it.

    • Abstract base classes are really often misused to "reuse code" (instead of a real inheritance). This applies to inheritance in general.

    The question should be: "When should I use Interfaces, extension methods or base classes?"

    • use interfaces whenever you need a contract (and this happens all the time).
    • Use (abstract) base classes when you have a situation for real inheritance (you could write a book about how to judged that, so I just leave it like this). An interface is mostly also implemented at the same time.
    • use extension methods for logic that should not be actually a member of the type, because it is not the responsibility of the type to implement it - but you want to make it easy to find and and it feels natural to call it like a member.

    Edit:

    Or the question should be: "How do I write reusable functionality that does not belong to a base class?"

    • write an interface that exposes the functionality
    • write a reusable library class that implements the functionality
    • write a class that implements the interface and reuses the functionality by aggregating the reusable class.

    In general I would say, extension methods are the wrong place for business logic, except of special cases or special design decisions.

    Base classes are only in rare cases the right decision. In doubt, it is not. In no-doubt, you should think again about it.

提交回复
热议问题