Interface vs Base class

后端 未结 30 2553
甜味超标
甜味超标 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:41

    I usually don't implement either until I need one. I favor interfaces over abstract classes because that gives a little more flexibility. If there's common behavior in some of the inheriting classes I move that up and make an abstract base class. I don't see the need for both, since they essentially server the same purpose, and having both is a bad code smell (imho) that the solution has been over-engineered.

    0 讨论(0)
  • 2020-11-21 07:42

    In general, you should favor interfaces over abstract classes. One reason to use an abstract class is if you have common implementation among concrete classes. Of course, you should still declare an interface (IPet) and have an abstract class (PetBase) implement that interface.Using small, distinct interfaces, you can use multiples to further improve flexibility. Interfaces allow the maximum amount of flexibility and portability of types across boundaries. When passing references across boundaries, always pass the interface and not the concrete type. This allows the receiving end to determine concrete implementation and provides maximum flexibility. This is absolutely true when programming in a TDD/BDD fashion.

    The Gang of Four stated in their book "Because inheritance exposes a subclass to details of its parent's implementation, it's often said that 'inheritance breaks encapsulation". I believe this to be true.

    0 讨论(0)
  • 2020-11-21 07:44

    Let's take your example of a Dog and a Cat class, and let's illustrate using C#:

    Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general). Let us assume that you have an abstract class Mammal, for both of them:

    public abstract class Mammal
    

    This base class will probably have default methods such as:

    • Feed
    • Mate

    All of which are behavior that have more or less the same implementation between either species. To define this you will have:

    public class Dog : Mammal
    public class Cat : Mammal
    

    Now let's suppose there are other mammals, which we will usually see in a zoo:

    public class Giraffe : Mammal
    public class Rhinoceros : Mammal
    public class Hippopotamus : Mammal
    

    This will still be valid because at the core of the functionality Feed() and Mate() will still be the same.

    However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of. That's where an interface will be useful:

    public interface IPettable
    {
        IList<Trick> Tricks{get; set;}
        void Bathe();
        void Train(Trick t);
    }
    

    The implementation for the above contract will not be the same between a cat and dog; putting their implementations in an abstract class to inherit will be a bad idea.

    Your Dog and Cat definitions should now look like:

    public class Dog : Mammal, IPettable
    public class Cat : Mammal, IPettable
    

    Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need into a class without the need for inheritance.

    Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly as required basis.

    0 讨论(0)
  • 2020-11-21 07:44

    Prefer interfaces over abstract classes

    Rationale, the main points to consider [two already mentioned here] are :

    • Interfaces are more flexible, because a class can implement multiple interfaces. Since Java does not have multiple inheritance, using abstract classes prevents your users from using any other class hierarchy. In general, prefer interfaces when there are no default implementations or state. Java collections offer good examples of this (Map, Set, etc.).
    • Abstract classes have the advantage of allowing better forward compatibility. Once clients use an interface, you cannot change it; if they use an abstract class, you can still add behavior without breaking existing code. If compatibility is a concern, consider using abstract classes.
    • Even if you do have default implementations or internal state, consider offering an interface and an abstract implementation of it. This will assist clients, but still allow them greater freedom if desired [1].
      Of course, the subject has been discussed at length elsewhere [2,3].

    [1] It adds more code, of course, but if brevity is your primary concern, you probably should have avoided Java in the first place!

    [2] Joshua Bloch, Effective Java, items 16-18.

    [3] http://www.codeproject.com/KB/ar...

    0 讨论(0)
  • 2020-11-21 07:44

    Previous comments about using abstract classes for common implementation is definitely on the mark. One benefit I haven't seen mentioned yet is that the use of interfaces makes it much easier to implement mock objects for the purpose of unit testing. Defining IPet and PetBase as Jason Cohen described enables you to mock different data conditions easily, without the overhead of a physical database (until you decide it's time to test the real thing).

    0 讨论(0)
  • 2020-11-21 07:45

    Modern style is to define IPet and PetBase.

    The advantage of the interface is that other code can use it without any ties whatsoever to other executable code. Completely "clean." Also interfaces can be mixed.

    But base classes are useful for simple implementations and common utilities. So provide an abstract base class as well to save time and code.

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