Reason to use BOTH abstract classes and interfaces? (Abstract class implements interface) - c#

Recently I have come across a curious pattern in some code. We know that there is a time and a place for everything, especially when it comes to the issue of ABCs and interfaces, but this just seems redundant to me.
// This describes a person....
public interface IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int BasePay { get; set; }
public string Address { get; set; }
}
// And so does this, but it also uses the interface....
public abstract class Person : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int BasePay { get; set; }
public string Address { get; set; }
}
// This uses both ?!
public class CoalMiner : Person, IPerson
{
public CoalMiner()
{
BasePay = 10000;
}
}
Can anybody think of what the specific advantage of using both and ABC and an interface that define the same members be?

Personally, I feel that using an interface to describe a "noun", such as a person, it typically a poor design choice.
Interfaces should be used for contracts - all people are always a Person, so an abstract class makes more sense here. Interfaces could be added for behaviors attached to specific types of people, or to allow a Person to be used in a certain way by fulfilling a contract (ie: Person : IComparable<Person>).

Having both the IPerson interface and the Person base class allows you certain freedoms, as long as you are passing around objects under the IPerson interface rather than the Person base class.
Base classes tend to implement common code that should be used by all descendants of that base class. That's fine if that's what you want, but one might run into a case where an entirely different implementation of IPerson is needed, where the base class Person is not used at all. Now you have 2 class hierarchies that have IPerson in common, and things still work. You would not be able to do that with Person only.
Another good reason for the redundancy of always having an interface would be for COM interop.

A situation where both the interface and the ABC makes sense is when using the decorator pattern. The ABC is used to provide common implementation code for the different concrete implementation classes. All implementation classes are probably derived from the ABC.
A decorator, which wraps an existing instance and tweaks the functionality of it would typically only implement the interface and not derive from the ABC. If there are many decorators, there could be another ABC which provides the common composition handling and function call forwarding that the decorators need.
Explicitly mentioning the interface sometimes makes it more readable. The MSDN documentation often do that, e.g. showing that List<> implements both ICollection<> and IList<> although IList<> is derived from ICollection<>.

The only advantage I could think of with a derived class explicitly implementing the same interface as its base class is to prohibit the derived class from hiding a member and as a result breaking the interface.

Interfaces specify a contract for behavior, so this only makes sense if you have sufficient behavior (beyond simple property accessors) that a non-Person might want to implement IPerson. For instance, if IPerson could HoldConversation(Stream input, Stream output), then you might have a TuringTestCandidate that implements IPerson, without actually deriving from Person.
In more practical terms, this pattern is typically used when you want to unit test behaviors of some class that depends on the interface and you don't want the overhead or possible interference from changes in the base class. It wouldn't make sense for this simplified example, but is often useful in practice.

In this case, your interface and abstract class are quite redundant, except that the abstract class is fulfilling the method requirement of the interface. I don't see the need for the interface in this case, especially given that there is an abstract class.
If you were to be implementing methods on objects with two arms and two legs -> IThingWithArmsAndLegs::DoTheHokeyPokey() that could be a good use of an interface. Then this interface could be shared among Person : IThingWithArmsAndLegs, and Alien : IThingWithArmsAndLegs.

I am a fan of both in the right situation, Why?
Even if you need just an Interface for some type of IOC/DI, it provides no common functionality. You can do this to Inject and have the base functionality covered through a common abstract base class. Then only abstract/virtual methods as needed.
It is oop at it's finest IMHO. Especially in a multi target solution.
I will make my Interfaces one time for all devices, then for each device create an Abstract Class that covers all the same common functionality common to that device type.

Just for the sake of argument you could have common functionality in the abstract Person base class that not everything implementing the interface IPerson needs to reduce duplicate code. At the same time you could have some routines that expect an IPerson to perform some common logic.
Having said that, I wouldn't recommend this practice this at all.

To me it looks bad specify Person and IPerson in the declaration of CoalMiner. I would just derive it from Person. The structur interface -> abstract class -> concrete class is fine with me, but overkill in most situations. I use it sometimes if most of the classes implementing the interface share a lot of code. So deriving from the abstract class is the default case for the 95% simple cases, but I would like to keep the option to have completly independent implementation of the interface.

Interfaces tend to be used a lot in Dependency Injection scenarios because they are considered "light weight" dependencies. Using this approach you tend to have interfaces defining a lot of things, and often end up with abstract classes that implement the interface to provide the base implementation of some or all of the interface members.
I tend to think this is a little extreme, particularly in the example you provided where the abstract class does not provide anything beyond the properties. I have to say I've been guilty of this myself at times, generally using the excuse that the interface makes it more "testable", and is friendlier to my IoC container of choice. I've been trying to reduce the interface bloat in my code recently that comes from a general mentality that loose-coupling via interfaces are required for proper Dependency Injection, realizing that there is a point where things just become silly.

While there is no NEED for CoalMiner to have the IPerson interface, I know some people prefer that so it is obvious that the type implements the interface. That being said, I don't this it is very useful like that.
Interfaces to define nouns are very common in enterprise systems where you may need to support multiple data access layers (DAL) because your system deals with multiple other systems. In this case you might have the following abstract classes
public interface ICustomer {}
public abstract class SapEntity {}
public abstract class NHibernateEntity {}
public class SapCustomer : SapEntity, ICustomer {}
public class NHibernateCustomer : NHibernateEntity, ICustomer {}
public class CustomerProcessor
{
public ICustomer GetCustomer(int customerID)
{
// business logic here
}
}

I find I often need to use both with generic base classes. Usually at some point I need to pass a reference to the open class generic base class which unfortunately you can't do in C#, so I create a non-generic interface.

I can see the point of having both the interface and abstract class (the interface defines the contract, and the abstract class can have a partial implementation that derived classes can share).
However, specifying both the parent class and the interface in the derived class is redundant (It's already implied because the abstract class must implement the interface or it won't compile).
This pattern might just be there as a coding standard so that it is obvious to other programmers when looking at the concrete class that its ancestors implement that interface.

None, if you extend the same interface twice, it's only used the first time. You can delete the 2nd IPerson and your code will still run fine.

Related

Cast from interface to class, bad design or small violation?

I have a question on how to be in cases when I build the hierarchy on interface, then I have the base abstract implementing class and many subclasses - concrete implementors.
But say one of the subclasses has 2 extra properties that are not included in the interface. But I need them when I work with interface. Is it a bad practice to cast from interface to the direct concrete class? Or maybe I would formalize this case (2 extra properties not included in interface) as a new extension of base interface through inheritance,
when one interface inherits from another one, so it would be safe to cast not to class, but to derived interface. What choice is the most corrective?
Here's an example:
public interface IToken {
string Tag {get;}
string Content {get;}
object CalculatedValue {get; set;}
string ValueFormat {get;}
}
// inheritance of interface
public interface ISimpleToken: IToken {
string Key {get; set;}
}
// OR!!!!!
class SimpleToken: IToken {
// ....interface members
....
public string Key {get; set; }
}
The general rule of thumb is if you are going to expose your API through interfaces, you should uses interfaces throughout. Your interfaces should only include things you want to publicly expose. If it's something you just need inside of the implementation of that interface it goes in the class.
The other part, "it depends". Usually with the way you are headed, at some point, you're going to want a collection of all of those implementations and so you would need to refer to them by the common base interface/class.
EDIT: if you find that you need to cast interfaces from the base class, you are "probably" doing something wrong. If multiple interfaces have the same method, it belongs in the base interface. You can do this with generics.
If you have a scenario where the derived classes need to do something different from the base class, then you should use virtual methods and overrides.
Adding something into a derived class is fine as long as it doesn't change the interface which it shouldn't since if you are using interfaces, you generally don't want to expose the implementation classes.

(Regular Class + interface) vs Abstract class

I recently encountered a question on abstract class.
Functionality of Abstract classes can be achieved by using combination of (Regular class with Protected Constructor + an interface).
What is the benefit of using Abstract Class over (Regular class with protected constructor + interface).
IMHO, Purpose of Abstract class to have common feature that needs to be available across the class hierarchy. It can pose restriction on sub-classes to implement certain features by Abstract methods. It can allow Sub-Classes to override the common behavior.
Abstract Class doesn't serve a purpose of as concrete object. So, It doesn't allow to instantiate the abstract class.
However,We can achieve same thing using Regular Class + interface.
Mark Regular Class constructor as protected, So object can't be created alone
provide default implementation of common features and mark them virtual in case if they need to be overridden by sub class.
Use interface to force sub-classes to implement certain features.
So, Is there any extra feature which Abstract class offer?
I could not think of any other. Interviewers was trying to know what other benefits Abstract class have over Regular Class with protected constructor + interface.
A lot of good reasons. Let's start with an unambiguous one:
public abstract class Smell
{
public abstract string GetAdjective();
public string GetDescription()
{
return "I smell " + GetAdjective();
}
}
public class NastySmell : Smell
{
public override string GetAdjective() { return "really nasty"; }
}
Pretty simple. The abstract class has a function, GetDescription - which relies on the presence of an abstract method GetAdjective.
How could you do this with ProtectedConstructor+Interface? You can't have Smell implement the interface (for lots of reasons, but a big one being that any derived classes would also inherit the implementation and wouldn't be required to implement anything new) - but that means that it's function can't refer to the method:
public interface SmellInterface
{
string GetAdjective();
}
public class Smell
{
protected Smell() { }
public string GetDescription()
{
// how do I call GetAdjective here? I have no reference to it!
}
}
But here's another, even more compelling reason:
public abstract class SomeFancyClass
{
protected string name;
protected string server;
protected abstract string implementer { get; }
public string Generate()
{
if (name == "something")
HandleGlobally(name);
else
HandleSpecifically(name);
}
public void HandleGlobally(string server)
{
// code
}
public abstract void HandleSpecifically(string server);
}
... if you make this class a combo ProtectedConstructorClass + Interface, you split up code into two separate spots - and suddenly, you have to look through two halves to get the full picture of what's going on!
public interface AbstractHalf
{
// data property of 'implementer'
// method of 'HandleSpecifically()
}
public class NonabstractHalf
{
// data fields of 'name' and 'server'
// methods of 'Generate()' and 'HandleGlobally'
}
... why would you want to do this? Your class is a distinct, logical entity. Why would you split it up into two separate parts: the non-abstract versus the abstract? It'd just make it harder to read and troubleshoot. And it'd get worse, the more code and abstract declarations were made in the class.
The main benefit of the abstract class is to force the developer to create a subclass that inherits from the abstract class in order to use base/shared functionality and fields.
You cannot directly new-up an abstract class. You can new-up a regular class + interface, and you are not forced to inherit or override anything in the base.
With an abstract class, you can reduce the number of files - i.e. no interfaces, but most folks would probably like to keep those for registration with an IoC container and dependency injection.
One thing that I can think of is that by using an abstract class you can force a specific implementation simply by not marking a method or property as virtual, while using an interface you can't prevent classes from implementing the interface but not derive from your base class.
Another benefit of using an abstract class is that you can simply add functionality to your abstract class without having to worry about having all your derived classes implementations - again, since you can't prevent a class from implementing an interface without deriving from your base class.
Also, an abstract class can have protected fields, methods, events etc', but an interface can't.
It all boils down to the fact that you can't force classes that implement your interface to derive from your "regular" base class.
First of all, there is many questions and answers about differences between Abstract Class and Interfaces like: this. There are a lot of remarkable answers. But most of them are about programming and syntax.
I want to look from Design Perspective:
I think that Abstract Class can not play the Role of Interface (+ Regular Class)
in Software Design.
Abstract Class:
The main goal of Abstract Class is Abstraction Principle. To overcome this complexity, Abstract classes are used to make Hierarchies in similar looking classes. All classes in the hierarchy are extending base classes functionalities and extending types of base classes.
Interface:
However, Interfaces are used for Interactions between classes. These classes can be similar or not. They can be from different hierarchies and different types.
Also, they are huge difference between inheriting from a class (even Abstract class) and implementing an interface. Interfaces are not TYPES. They are shared boundary across which two or more separate components of a computer system exchange information.

Is it a good practice to add public methods in a class which are not in Interface definition? When should I do that?

Not very clear with OOP concepts, could be a silly question, please ignore the silliness of it :-)
The question is related to the class below. There I have added a public method "TestMethod()", which is not defined in the interface (below).
Is it a bad practice? Should all methods must be defined in Interface?
In which cases am I allowed to implement a public methods/members in a class, but not in an Interface?
The Interface...
public interface IAnimals
{
void MakeNoise(string noise);
void Move();
string Color
{
get;
set;
}
}
The Class Implementation...
class Animal : IAnimals
{
private string color;
string IAnimals.Color
{
get
{
return color;
}
set
{
color = value;
}
}
void IAnimals.MakeNoise(string noise)
{
Console.WriteLine("Animal " + noise);
}
void IAnimals.Move()
{
Console.WriteLine("Animal moves");
}
public void TestMethod()
{
Console.WriteLine("test method in Animal class");
}
}
The Program...
class Program
{
static void Main(string[] args)
{
//Animal1 show methods and properties defined in the Interface
IAnimals animal1 = new Animal();
//Animal2 only shows the public method of Animal class
Animal animal2 = new Animal();
animal1.Color = "Red";
Console.WriteLine("Animal's color is " + animal1.Color);
animal1.MakeNoise("Barks");
animal1.Move();
animal2.TestMethod();
Console.ReadLine();
}
}
And The Output...
Animal's color is Red
Animal Barks
Animal moves
test method in Animal class
My approach would go something like this.
A class should aim to have one responsibility (Single Responsibility Principle), and its public contract (namely, publicly accessible members) should be relevant to the responsibility it fulfils.
I would not attempt to enforce a correlation between concrete class public members and interface public members. A class may have a public member in order to fulfil a cross-cutting concern that isn't pertinent to the interface contract it is implementing, but is entirely pertinent to the implementation detail. Or it may even be implementing multiple interfaces or some that don't mean anything to its responsibility (such as IDisposable).
It depends on how you expose this contract as to whether this is a potential issue or not. I tend to expose interfaces to offer behaviour, as it allows me to use DI containers etc to manage implementation configurations, which in turn allows me to either mock the interface or provide a test implementation for the purposes of unit testing. That said, if you are handing around concrete types (which are also valid "contracts") then the public face of that type forms an implied contract, so you need to be careful of changing that (just as you would be careful changing interface definitions).
I never particularly worry that I have a type that has more public members than the interface does, but I do try to pay attention to what the type is trying to do (and look out for when it is trying to do too much).
So I would answer that it is good practice to review what responsibilities a class is trying to cover and attempt to minimise that to one, but I would say this public member comparison isn't a relevant "code smell" alert, in my opinion.
The interface definition declares only the properties and methods that makes the implementation comply with the 'contract'.
You will almost never have only the properties and methods defined in the interface in your class, since the class usually needs some more that a general contract implementation.
A good example in a class definition that deviates from the interface is a class implementing ICloneable. You need to implement the Clone method, but that doesn't describe what the class actually does, it just implements that contract the class has with the interface.
In some cases, a class will exist primarily for the purpose of satisfying an interface; if a class exists for the purpose of implementing interface IWuzzler and the most natural description for an instance of the class would be "a Wuzzler", then it may be good to have the public face of the class match the interface as well as possible; the fact that a member would be useful in the class would suggest that it might be useful as a [possibly optional] part of the interface.
In other cases, however, a class will exist for its own purposes but will satisfy an interface so that it can be operated upon by code that isn't apt to care about most of the things the class does. For example, many collection types might implement IEnumerable<T> even though their primary purpose centers around things that most consumers of IEnumerable<T> would know nothing about. If the class implements an interface for the purpose of making instances usable by outside general-purpose code, then the type should be expected to have many members which are not present in those interfaces.

implementing polymorphism in c#, how best to do it?

first question here, so hopefully you'll all go gently on me!
I've been reading an awful lot over the past few days about polymorphism, and trying to apply it to what I do in c#, and it seems there are a few different ways to implement it. I hope I've gotten a handle on this, but I'd be delighted even if I haven't for clarification.
From what I can see, I've got 3 options:
I can just inherit from a base
class and use the keyword
'virtual' on any methods that I
want my derived classes to
override.
I could implement an abstract class with virtual methods
and do it that way,
I could use an interface?
From what I can see, if I don't require any implementation logic in the base, then an interface gives me the most flexibility (as I'm then not limiting myself with regards multiple inheritance etc.), but if I require the base to be able to do something on top of whatever the derived classes are doing, then going with either 1 or 2 would be the better solution?
Thanks for any input on this guys - I have read so much this weekend, both on this site and elsewhere, and I think I understand the approaches now, yet I just want to clarify in a language specific way if I'm on the right track. Hopefully also I've tagged this correctly.
Cheers,
Terry
An interface offers the most abstraction; you aren't tied to any specific implementation (useful if the implementation must, for other reasons, have a different base class).
For true polymorphism, virtual is a must; polymorphism is most commonly associated with type subclassing...
You can of course mix the two:
public interface IFoo {
void Bar();
}
class Foo : IFoo {
public virtual void Bar() {...}
}
class Foo2 : Foo {
public override ...
}
abstract is a separate matter; the choice of abstract is really: can it be sensibly defined by the base-class? If there is there no default implementation, it must be abstract.
A common base-class can be useful when there is a lot of implementation details that are common, and it would be pointless to duplicate purely by interface; but interestingly - if the implementation will never vary per implementation, extension methods provide a useful way of exposing this on an interface (so that each implementation doesn't have to do it):
public interface IFoo {
void Bar();
}
public static class FooExtensions {
// just a silly example...
public static bool TryBar(this IFoo foo) {
try {
foo.Bar();
return true;
} catch {
return false;
}
}
}
All three of the above are valid, and useful in their own right.
There is no technique which is "best". Only programming practice and experience will help you to choose the right technique at the right time.
So, pick a method that seems appropriate now, and implement away.
Watch what works, what fails, learn your lessons, and try again.
Interfaces are usually favored, for several reasons :
Polymorphisme is about contracts, inheritance is about reuse
Inheritance chains are difficult to get right (especially with single inheritance, see for instance the design bugs in the Windows Forms controls where features like scrollability, rich text, etc. are hardcoded in the inheritance chain
Inheritance causes maintenance problems
That said, if you want to leverage common functionnality, you can use interfaces for polymorphism (have your methods accept interfaces) but use abstract base classes to share some behavior.
public interface IFoo
{
void Bar();
enter code here
}
will be your interface
public abstract class BaseFoo : IFoo
{
void Bar
{
// Default implementation
}
}
will be your default implementation
public class SomeFoo : BaseFoo
{
}
is a class where you reuse your implementation.
Still, you'll be using interfaces to have polymorphism:
public class Bar
{
int DoSometingWithFoo(IFoo foo)
{
foo.Bar();
}
}
notice that we're using the interface in the method.
The first thing you should ask is "why do I need to use polymorphism?", because polymorphism is not and end by itself, but a mean to reach an end. Once you have your problem well defined, it should be more clear which approach to use.
Anyway, those three aproaches you commented are not exclusive, you still can mix them if you need to reuse logic between just some classes but not others, or need some distinct interfaces...
use abstract classes to enforce a class structure
use interfaces for describing behaviors
It really depends on how you want to structure your code and what you want to do with it.
Having a base class of type Interface is good from the point of view of testing as you can use mock objects to replace it.
Abstract classes are really if you wish to implement code in some functions and not others, as if an abstract class has nothing other than abstract functions it is effectively an Interface.
Remember that an abstract class cannot be instantiated and so for working code you must have a class derived from it.
In practice all are valid.
I tend to use an abstract class if I have a lot of classes which derive from it but on a shallow level (say only 1 class down).
If I am expecting a deep level of inheritence then I use a class with virtual functions.
Eitherway it's best to keep classes simple, along with their inheritence as the more complex they become the more likelyhood of introducing bugs.

Abstract classes vs Interfaces

I'm a bit confused about the usage of Abstract classes in C#. In C++, it makes sense to define a template which classes inheriting the abstract class can follow. But, in C# doesn't Interface serve the same purpose?
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
I still like to provide a default abstract implementation of an interface, assuming it's a substantial interface (and it makes sense). You never know when you might add something to the interface that has an easy default implementation that could be included and given "for free" to anyone who inherits from the abstract base class.
This CodeProject article has a lot of information on the difference between the two including a table comparing and contrasting the features of each.
Interfaces define the contract between classes - the ways classes call each other. A class can implement multiple interfaces, but can only inherit from one abstract class.
True that abstract classes can have default implementation which is not provided by Interfaces. So if implementation doesn't need to be included in base class, is it better to go for Interfaces?
Yes :). If it makes sense to implement some methods in the base class which will be common to all inhereted class you should use an abstract class. If the base class would only be used to define an interface but there is no common logic between the inherited classes, use an interface.
Interfaces and abstract classes serve different goals. Interfaces are used to declare contracts for classes while abstract classes are used to share a common implementation.
If you only use abstract classes, your classes cannot inherit from other classes because C# does not support multiple inheritance. If you only use interfaces, your classes cannot share common code.
public interface IFoo
{
void Bar();
}
public abstract class FooBase : IFoo
{
public abstract void Bar()
{
// Do some stuff usually required for IFoo.
}
}
Now we can use the interface and base implementation in various situations.
public class FooOne : FooBase
{
public override void Bar()
{
base.Bar(); // Use base implementation.
// Do specialized stuff.
}
}
public class FooTwo : FooBase
{
public override void Bar()
{
// Do other specialized stuff.
base.Bar(); // Use base implementation.
// Do more specialized stuff.
}
}
// This class cannot use the base implementation from FooBase because
// of inheriting from OtherClass but it can still implement IFoo.
public class FooThree : OtherClass, IFoo
{
public virtual void Bar()
{
// Do stuff.
}
}
For your first question, Yes.
For your second answer i'll give you some tips I've followed.
Use abstract classes and interfaces in combination to optimize your design trade-offs.
Use an abstract class
When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning.
Use an abstract class to define a common base class for a family of types.
Use an abstract class to provide default behavior.
Subclass only a base class in a hierarchy to which the class logically belongs.
Use an interface
When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
Use an interface to design a polymorphic hierarchy for value types.
Use an interface when an immutable contract is really intended.
A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.
You can implement any number of Interfaces, but can only inherit one Class. So Classes and Interfaces are quite different beasts in C# and you cannot use them interchangeably. In C# abstract classes are still classes, not interfaces.
If you don't have any default/common code, then go with an interface.
An abstract class can also serve as a template, where it defines the steps of some algorithm and the order in which they are called, and derived classes provide the implementation of these steps:
public abstract class Processor
{
// this is the only public method
// implements the order of the separate steps
public void Process()
{
Step1();
Step2();
//...
}
// implementation is provided by derived classes
protected abstract void Step1();
protected abstract void Step2();
}
Whilst it's true that an abstract class with no implementation is equivalent to an interface, interfaces and abstract classes are used for different things.
Interfaces can be used for polymorphism in the most general sense. For example, ICollection is used to define the interface for all collections (there are quite a few). Here it is defining the operations that you want to perform on a certain kind of type. There are many other uses (such as testability, dependency injection etc). Also, interfaces can be mixed and this works both conceptually and technically.
Abstract classes are more to do with templateable behaviour, where virtual methods are a place to 'fill in the gaps'. Obviously you can't mix abstract classes (at least, not in C#).
In C# a large deterrent for the use of abstract classes is that you can only use one. With interfaces you have the advantage of not limiting the base class for the implementation. To this end, I always use an interface even if I create an abstract base class to aid with the implementation.
Often another annoyance of base abstract classes is that they tend to rely on template arguments. This can make it very difficult for the rest of your code to utilize. The easy answer for this is to provide an interface to talk to the abstract class without knowing the type argument of the template class.
Others seem to be typing their answer faster, but allow me to summarize...
Use an interface. If you need to share implementation, you can also create an abstract base class that provides common implementation details.
Note that with C#3, you can provide default behavior for interfaces through the use of extension methods. There are some limitations, though, and abstract classes still have their place.
The rule I follow when modeling is:
Classes(abstract included) and structs model entities.Interfaces model behavior.
Entities implementing an interface can be considered as exhibiting behaviors that the interface(contract) exposes.
This is hinted at in a few of the answers but not explicitly stated.
The fact that you can implement multiple interfaces and only inherit from one base class, as if they were two sides of the same coin, isn't a good way to look at it.
Don't think of interfaces as part of an object hierarchy. They are usually just small parts of functionality (or at least specific if not small) that your real object heirarchy can declare as implementing. Take IDisposable for instance. If you were the one writing that, would you ask yourself whether it should have been an abstract class or an interface? It seems obvious that in this case they are two completely different things. I want to BE disposable. Think ICloneable and IEnumerable. You can implement those in your class without having to try and make your class derive from some unrelated classes like List or Array. Or take IEnumerator. Simply gives a MoveNext type of view to an object. My class can provide that functionality without having to awkwardly be derived from some other sequential collection data type that has nothing to do with my class.
I always prefer interfaces as long as the base class don't have some really "heavy duty" implementation that will save lots of time to the implementers.
giving that .net allows only one base class inheritance, forcing your users to inherit is a huge limitation.
You should always prefer programming to interfaces than to concrete classes.
If you also want to have a default implementation you can still create a base class which implements your interface(s).

Categories