Interface + Extension (mixin) vs Base Class

后端 未结 3 1570
忘掉有多难
忘掉有多难 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 09:59

    Interfaces tend to make code a little cleaner I feel it's a little easier to test. When you add Extensions your adding even more flexibility while keeping clean testable code.

    For me abstract classes have always seemed clunky, using interfaces I can have an object factory that returns an object that is specific to what I'm trying to accomplish (separation of concerns).

    Just making something up A have the interface called Math that has add, subtract, divide and multiply and then I have a class called IntMAth that implements Math that is optimized for integer math, and I have another class called FloatMath the implements Math that is optimized for Floating Math, and I have a generalMath that implements Math that handles everything else.

    When I need to Add some floats I could call my factory MathFactory.getMath(typeof(float)) and it has some logic to know that if the type I'm passing in is a float then it returns the FloatMath class.

    This way all of my classes are smaller and more maintainable, the code that calls the classes is smaller, etc.

提交回复
热议问题