How to Interface or Abstract Base Class in C Sharp 4.0?
When designing class hierarchies, you often need to decide whether classes at the
root of the hierarchy (the parent classes) should be abstract base classes, or
whether to implement the concrete classes in terms of interfaces.
Here are some guidelines to help make this decision.
In favor of interfaces:
. Will classes need to implement multiple base classes? This isn’t possible in C#,
but it is possible to implement multiple interfaces.
. Have you separated concerns to the point where you understand the difference
between what your class is and what it does? Interfaces are often about what the
class does, whereas a base class can anchor what it is.
. Interfaces are often independent of what a class is and can be used in many situations.
They can be added onto the class without concern for what it is.
. Interfaces often allow a very loosely coupled design.
. Deriving too many things from a base class can lead to it being bloated with too
In favor of base classes:
. Is there reasonable common functionality or data for all derived types? An
abstract base class may be useful.
. Implementing the same interface over many types can lead to a lot of repetition
of code, whereas an abstract base class can group common code into a single
. An abstract base class can provide a default implementation.
. Abstract base classes tend to rigidly structure code. This may be desirable in
If you find yourself trying to put too much functionality into abstract base classes,
another possibility is to look into componentizing the various areas of functionality.
As you gain experience, you'll come to realize what makes sense in different situations.
Often, some combination of the two makes sense.
|All times are GMT +5.5. The time now is 11:50.|