Interface vs Base class

后端 未结 30 3011
甜味超标
甜味超标 2020-11-21 07:34

When should I use an interface and when should I use a base class?

Should it always be an interface if I don\'t want to actually define a base implementation of the

30条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 07:52

    Interfaces

    • Defines the contract between 2 modules. Cannot have any implementation.
    • Most languages allow you to implement multiple interfaces
    • Modifying an interface is a breaking change. All implementations need to be recompiled/modified.
    • All members are public. Implementations have to implement all members.
    • Interfaces help in Decoupling. You can use mock frameworks to mock out anything behind an interface
    • Interfaces normally indicate a kind of behavior
    • Interface implementations are decoupled / isolated from each other

    Base classes

    • Allows you to add some default implementation that you get for free by derivation
    • Except C++, you can only derive from one class. Even if could from multiple classes, it is usually a bad idea.
    • Changing the base class is relatively easy. Derivations do not need to do anything special
    • Base classes can declare protected and public functions that can be accessed by derivations
    • Abstract Base classes can't be mocked easily like interfaces
    • Base classes normally indicate type hierarchy (IS A)
    • Class derivations may come to depend on some base behavior (have intricate knowledge of parent implementation). Things can be messy if you make a change to the base implementation for one guy and break the others.

提交回复
热议问题