For my new Pet-Project I have a question for design, that is decided already, but I want some other opinions on that too.
I have two classes (simplified):
class MyObject
{
string name {get;set;}
enum relation {get;set;}
int value {get;set;}
}
class MyObjectGroup
{
string name {get;set;}
enum relation {get;set;}
int value {get;set;}
List<MyObject> myobjects {get;set;}
}
Later in the Project MyObjectGroup
and MyObject
should be used equally. For this I could go two ways:
- Create an interface:
IObject
- Create an abstract class:
ObjectBase
I decided to go the way of the interface, that I later in code must not write ObjectBase
every time but IObject
just for ease - but what are other positives for this way?
And second, what about adding IXmlSerializable
to the whole story?
Let the interface inherit from IXmlSerializable
or does it have more positives to implement IXmlSerializable
in abstract base class?
Note that you cannot override operators in Interfaces. That is the only real problem with them as far as I'm concerned.
Generally, you should consider interfaces as contracts that some types implement and abstract classes as nodes in inheritance hierarchy that don't exist by themselves (i.e. there is an "is a" relationship between the derived class and the base abstract class). However, in practice, you might need to use interfaces in other cases, like when you need multiple inheritance.
For instance,
IXmlSerializable
is not an "entity" by itself. It defines a contract that an entity can implement. Interfaces live "outside" the inheritance hierarchy.You could actually go with BOTH. ObjectBase saves you the trouble of implementing the common properties more than once and implements IObject for you. Everywhere you use it refer to IObject so you can do testing with mocks later