Implement unnecessary Interface members or Create a new Interface? - c#

General architecture problem i have been thinking about
If I have an interface, and 5 classes that implement that interface, but one class does not need to implement one of the interface members, should I:
Create a seperate interface for that one class
Implement the
original interface but leave the methods empty
Implement the original interface but mark the unneccessary methods in some way
(e.g obsolete attribute)
An example is if I have an interface IRepository and 5 seperate repositories for 5 entities, but for one entity I dont want to be able to update records.
I have currently sided toward option 3, but obsolete does not seem a correct description.
any ideas?
by the way I know this is quite broad and objective but I would like to hear some opinions about the best way to go.

You could create another interface and inherite the ones you actually use
public interface IReadOnlyRepository
{
void Read();
}
public interface IRepository : IReadOnlyRepository
{
void Write();
}
Then you could use the 'base' interface IReadOnlyRepository for the class you don't want the full implementation for.
Or, using you number 3. when the user attempts to invoke C from a class that does not implement it. Throw a NotImplementedException/InvalidOperationException or other relevant exception.
I hope this helps.

Why not have 2 interfaces?
IReadableRepo
{
Data Read();
}
IUpdatableRepo : IReadableRepo
{
void Update();
}
Then implement the most relevant one in your classes.

The formal answer would be to split it into IRepository: IReadonlyRepository and implement only the interfaces that are applicable.
But as a practical approach, for just one case, you could throw a NotSupported exception from the Update() method. That's your option 3 but you cannot really mark it efficiently for compile-time feedback.

I am no expert in these matters, but from my point of view, I see an issue if you decide to stick with only one interface, it will seem you are offering a functionality that isn't supported.
In this case, you could have a base interface ReadableRepository extended by UpdateableRepository.
However, if for some reason you'll need a bit more properties for your repository, you might consider making separate interfaces for each (IDoable1, IDoable2, ..., IDoableN) and have your concrete classes implement what they need.

Related

What is the purpose to use an empty interface? [duplicate]

I am looking at nServiceBus and came over this interface
namespace NServiceBus
{
public interface IMessage
{
}
}
What is the use of an empty interface?
Usually it's to signal usage of a class. You can implement IMessage to signal that your class is a message. Other code can then use reflection to see if your objects are meant to be used as messages and act accordingly.
This is something that was used in Java a lot before they had annotations. In .Net it's cleaner to use attributes for this.
#Stimpy77 Thanks! I hadn't thought of it that way.
I hope you'll allow me to rephrase your comment in a more general way.
Annotations and attributes have to be checked at runtime using reflection. Empty interfaces can be checked at compile-time using the type-system in the compiler. This brings no overhead at runtime at all so it is faster.
Also known as a Marker Interface:
http://en.wikipedia.org/wiki/Marker_interface_pattern
In java Serializable is the perfect example for this. It defines no methods but every class that "implements" it has to make sure, that it is really serializable and holds no reference to things that cannot be serialized, like database connections, open files etc.
In Java, empty interfaces were usually used for "tagging" classes - these days annotations would normally be used.
It's just a way of adding a bit of metadata to a class saying, "This class is suitable for <this> kind of use" even when no common members will be involved.
Normally it's similar to attributes. Using attributes is a preferred to empty interfaces (at least as much as FxCop is aware). However .NET itself uses some of these interfaces like IRequiresSessionState and IReadOnlySessionState. I think there is performance loss in metadata lookup when you use attributes that made them use interfaces instead.
An empty interface acts simply as a placeholder for a data type no better specified in its interface behaviour.
In Java, the mechanism of the interface extension represents a good example of use. For example, let's say that we've the following
interface one {}
interface two {}
interface three extends one, two {}
Interface three will inherit the behaviour of 'one' and 'two', and so
class four implements three { ... }
has to specify the two methods, being of type 'three'.
As you can see, from the above example, empty interface can be seen also as a point of multiple inheritance (not allowed in Java).
Hoping this helps to clarify with a further viewpoint.
They're called "Mark Interfaces" and are meant to signal instances of the marked classes.
For example... in C++ is a common practice to mark as "ICollectible" objects so they can be stored in generic non typed collections.
So like someone over says, they're to signal some object supported behavior, like ability to be collected, serialized, etc.
Been working with NServiceBus for the past year. While I wouldn't speak for Udi Dahan my understanding is that this interface is indeed used as a marker primarily.
Though I'd suggest you ask the man himself if he'd had thoughts of leaving this for future extension. My bet is no, as the mantra seems to be to keep messages very simple or at least practically platform agnostic.
Others answer well on the more general reasons for empty interfaces.
I'd say its used for "future" reference or if you want to share some objects, meaning you could have 10 classes each implementing this interface.
And have them sent to a function for work on them, but if the interface is empty, I'd say its just "pre"-work.
Empty interfaces are used to document that the classes that implement a given interface have a certain behaviour
For example in java the Cloneable interface in Java is an empty interface. When a class implements the Cloneable interface you know that you can call run the clone() on it.
Empty interfaces are used to mark the class, at run time type check can be performed using the interfaces.
For example
An application of marker interfaces from the Java programming language is the Serializable interface. A class implements this interface to indicate that its non-transient data members can be written to an ObjectOutputStream. The ObjectOutputStream private method writeObject() contains a series of instanceof tests to determine writeability, one of which looks for the Serializable interface. If any of these tests fails, the method throws a NotSerializableException.
An empty interface can be used to classify classes under a specific purpose. (Marker Interface)
Example : Database Entities
public interface IEntity {
}
public class Question implements IEntity {
// Implementation Goes Here
}
public class Answer implements IEntity {
// Implementation Goes Here
}
For Instance, If you will be using Generic Repository(ex. IEntityRepository), using generic constraints, you can prevent the classes that do not implement the IEntity interface from being sent by the developers.

How do I implement an interface if I don't need all of its functions?

I have a simple interface defined
public interface IBla
{
public void DoThing();
public void DoAnotherThing();
public void Thing();
}
I have a bunch of classes which implement this interface. Lots of them however only need two of the three functions which that interface implements, so currently I implement the remaining ones as well and just leave them empty like so:
public void DoThing(){}
Is there some more elegant way of doing this?
I do NOT want to have multiple interfaces defined for this.
Is there perhaps something like a "partialInterface" where I don't have to implement all of the functions from that interface into a class which implements that interface?
Thanks
When implementing an interface, the type that implements the interface must provide an implementation for everything that interface details.
There is no support for partial interfaces or anything similar to what you want, other than breaking up the interface.
You're basically asking "How can I implement the calculator interface without requiring me to provide the + operator" and in short, you can't. It would no longer be a calculator according to that interface.
The closest thing you get is that you can create a base class that provides default implementations for the whole interface or parts of it, and inherit from this base type, so that inherited classes become easier to implement with less code, but they will provide the entire interface.
I know you said you don't want separate interfaces, but for the benefit of others in future who want the right answer to this question here it is:
What you describe is the point at which you separate your interfaces out, and use interface inheritance.
public interface IBasic
{
void DoThing();
}
public interface IAdvanced : IBasic
{
void DoAnotherThing();
void Thing();
}
Implementations which only need DoThing only implement IBasic. Implementations which need all functionality implement IAdvanced which includes the method from IBasic plus the additional functionality.
If you have classes which implement not all methods, then you probably need to separate this interface into smaller interfaces.
Many specific interfaces are better than one universal.
Creating the classes which implement your interface, and throw NotImplementedException or simply do nothing looks like SOLID rules violation.
Well, it is highly discouraged to only partially implement an interface, there is a way to sort of do it.
Most answers talk about breaking up your interface into multiple interfaces, which makes sense. But, if this is not possible simply implement the members that you do not want to use in an explicit manner, and if they get called you should throw a NotSupportedException.
If you want to see an example of this in use, look no further than Microsoft's own code: http://referencesource.microsoft.com/#mscorlib/system/collections/objectmodel/readonlycollection.cs
void ICollection<T>.Add(T value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
Given that these things are being processed in a game loop, presumably implementations of IBla are things like the player character, enemies, obstacles, missiles and the like and DoThing etc and Move, Fire and so forth.
If so, then your approach is perfectly valid. An immobile object should have a Move method (so the game loop can call it), and since it can't move, an empty method is a valid implementation.
If you control both interfaces then separate the interfaces into multiple interfaces. As suggested, one interface can inherit from the other, or you could just have some classes implement both interfaces.
In this case interface inheritance is probably the better choice because you won't have to modify the classes that already implement the larger interface.
What if the larger interface is one you don't control, so splitting it into multiple interfaces isn't an option? It's not a good idea to implement the interface and leave some methods without implementations. If a class implements an interface then it should really implement the interface.
A solution is to define the smaller interface that you actually want and create a class that adapts the larger interface to your smaller one.
Suppose you have this interface
public interface IDoesFourThings
{
void DoThingOne();
void DoThingTwo();
void DoThingThree();
void DoThingFour();
}
And you want a class that only implements two of those things? You shouldn't implement IDoesFourThings if the class really only does two things.
So first, create your own interface:
public interface IDoesTwoThings
{
void DoThingA();
void DoThingB();
}
Then create a class that adapts an implementation of IDoesFourThings to your interface.
public class DoesTwoThingsUsingClassThatDoesFourThings : IDoesTwoThings
{
private readonly IDoesFourThings _doesFourThings;
public DoesTwoThingsUsingClassThatDoesFourThings(IDoesFourThings doesFourThings)
{
_doesFourThings = doesFourThings;
}
public void DoThingA()
{
_doesFourThings.DoThingTwo();
}
public void DoThingB()
{
_doesFourThings.DoThingThree();
}
}
Just for the sake of example I avoided naming the methods in IDoesTwoThings to match the ones in IDoesFourThings. Unless they're really exactly the same thing then the new interface doesn't need to match the old one. It is its own interface. That the class works by using an inner implementation of IDoesFourThings is hidden.
This relates to the Interface Segregation Principle, the I in SOLID. One way of thinking about it is this: An interface describes what a class does, but from the perspective of the client class it should describe what the client needs. In this case the client needs two things, not four.
This approach can be very helpful because it enables us to work on one class at a time and defer the implementation of other details. If we're writing a class and we realize that it's going to require a dependency that does two things, we can just write the interface for those two things and make our class depend on it. (Now that class is more testable because it depends on an interface which we can mock.) Then, whatever that new interface is that we just created, we can also create an implementation for that.
It's a great way to manage the complexity of writing code and avoid getting stuck because now we can just work on our one class with its single responsibility, not worrying too much about how the next class and the next one will work. (We likely have an idea how they will work, but maybe we don't. Either way it doesn't slow us down.)

Object oriented design: when to make an abstract class

Right now, I am learning OOP, mainly in c#. I am interested in what are the main reasons to make a class that can't be instantiated. What would be the correct example of when to make an abstract class?
I found myself using the abstract class in inheritance way too enthusiastically. Are there some rules when class is abstract in system and when class should not be abstract?
For instance, I made doctor and patient classes which are similar in some way so I derived them both from abstract class Person (since both have name and surname). Was that wrong?
Sorry if the question is stupid, I am very new at this.
There are a couple of things no one has pointed out so far, so I would just like to point them out.
You can only inherit from one base class (which could be abstract) but you can implement many interfaces. So in this sense inheriting an abstract class is a closer relationship than implementing an interface.
So if you later on realize that you have a need for a class which implements two different abstract classes you are in deep shit :)
To answer your question "when to make an abstract class" I'd say never, avoid it if possible, it will never pay off in the long run, if the main class is not suitable as a ordinary class, it probably isn't really needed as abstract either, use an interface. If you ever get in the situation where you are duplicating code it might be suitable with an abstract class, but always have a look at interfaces and behavioral patterns first (ex the strategy pattern solves a lot of issues people wrongly use inheritance to solve, always prefer composition over inheritance). Use abstract classes as a last hand solution, not as a design.
To get a better understanding of OOP in general, I'd recommend you to have a look at Design Patterns: Elements of Reusable Object-Oriented Software (a book) which gives a good overview of OO-design and reusability of OO-components. OO-design is about so much more than inheritance :)
For Example: you have a scenario where you need to pull data from different sources, like "Excel File,XML,any Database etc" and save in one common destination. It may be any database. So in this situation you can use abstract classes like this.
abstract class AbstractImporter
{
public abstract List<SoldProduct> FetchData();
public bool UploadData(List<SoldProduct> productsSold)
{
// here you can do code to save data in common destination
}
}
public class ExcelImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from excel
}
}
public class XMLImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from XML
}
}
public class AccessDataImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from Access database
}
}
and calling can be like this
static class Program
{
static void Main()
{
List<SoldProduct> lstProducts;
ExcelImporter excelImp = new ExcelImporter();
lstProducts = excelImp.FetchData();
excelImp.UploadData(lstProducts);
XMLImporter xmlImp = new XMLImporter ();
lstProducts = xmlImp.FetchData();
xmlImp.UploadData(lstProducts);
AccessDataImporterxmlImp accImp = new AccessDataImporter();
lstProducts = accImp .FetchData();
accImp.UploadData(lstProducts);
}
}
So, in Above example, implementation of data import functionality is separated in extended (derived) class but data upload functionality is common for all.
This is probably a non-academic definition, but an abstract class should represent an entity that is so "abstract" that make no sense to instantiate it.
It is often used to create "templates" that must be extended by concrete classes. So an abstract class can implement common features, for example implementing some methods of an interface, an delegate to concrete classes implementation of specific behaviors.
In essence what you have done is fine if you never want to instantiate a Person class, however as I'm guessing you may want to instantiate a Person class at some point in the future then it should not be abstract.
Although there is an argument that you code to fix current issues, not to cater for issues which may never arise, so if you need to instantiate Person class do not mark it as abstract.
Abstract classes are incomplete and must be implemented in a derived class... Generally speaking I tend to prefer abstract base classes over interfaces.
Look into the difference between abstract classes and interfaces...
"The difference between an abstract class and an interface is that an abstract class can have a default implementation of methods, so if you don't override them in a derived class, the abstract base class implementation is used. Interfaces cannot have any implementation." Taken from this SO post
As already stated, noone will force you to use abstract classes, it is just a methodology to abstract certain functionality which is common among a number of classes.
Your case is a good example where to use abstract classes, because you have common properties among two different types. But of cause it restricts you to use Person as a type by itself. If you want to have this restriction is basically up to you.
In general, I would not use abstract classes for Model like classes as you have unless you want to prevent Person from being instantiated.
Usually I use abstract classes if I also have defined an interface and I need to code different implementations for this interface but also want to have a BaseClass which already covers some common functionality for all implementations.
Deriving both 'Doctor' and 'Patient' from an abstract class 'Person' is fine, but you should probably make Person just a regular class. It depends on the context in which 'Person' is being used, though.
For example, you might have an abstract class named 'GameObject'. Every object in the game (e.g. Pistol, OneUp) extends 'GameObject'. But you can't have a 'GameObject' by itself, as 'GameObject' describes what a class should have, but doesn't go into detail as to what they are.
For example, GameObject might say something like: "All GameObjects must look like something'. A Pistol might extend on what GameObject said, and it says "All Pistols must look like a long barrel with a grip on one end and a trigger."
The key is whether instantiation of that class ever makes sense. If it will never be appropriate to instantiate that class, then it should be abstract.
A classic example is a Shape base class, with Square, Circle and Triangle child classes. A Shape should never be instantiated because by definition, you don't know what shape you want it to be. Therefore, it makes sense to make Shape an abstract class.
Incidentally, another issue which hasn't yet been mentioned is that it is possible to add members to an abstract class, have existing implementations automatically support them, and allow consumers to use implementations which know about the new members and implementations which don't, interchangeably. While there are some plausible mechanisms by which a future .NET runtime could allow interfaces to work that way as well, at present they do not.
For example, if IEnumerable had been an abstract class (there are of course good many reasons why it isn't), something like a Count method could have been added when its usefulness became apparent; its default implementation of Count could behave much like the IEnumerable<T>.Count extension method, but implementations which knew about the new method could implement it more efficiently (although IEnumerable<T>.Count will try to take advantage of implementations of ICollection<T>.Count or ICollection.Count, it first has to determine whether they exist; by contrast, any override would know that it has code to handle Count directly).
It would have been possible to add an ICountableEnumerable<T> interface which inherited from IEnumerable<T> but included Count, and existing code would continue to work just fine with IEnumerable<T> as it always had, but any time an ICountableEnumerable<T> was passed through existing code, the recipient would have to recast it to ICountableEnumerable<T> to use the Count method. Far less convenient than having a directly-dispatched Count method which could simply act directly on IEnumerable<T> [the Count extension method isn't horrible, but it's far less efficient than would be a directly-dispatched virtual method].
If there were a means by which an interface could include static methods, and if the class loader, upon finding that a class Boz which claimed to implement IFoo, was missing method string IFoo.Bar(int), would automatically add to that class:
stringIFoo.Bar(int p1) { return IFoo.classHelper_Bar(Boz this, int p1); }
[assuming the interface contains that static method], then it would be possible to have interfaces add members without breaking existing implementations, provided that they also included static methods that could be called by default implementations. Unfortunately, I know of no plans to add any such functionality.

Using The Interface Methods I Want Based On The Implementation

I have two basic interface-related concepts that I need to have a better
understanding of.
1) How do I use interfaces if I only want to use some of the interface
methods in a given class? For example, my FriendlyCat class inherits from
Cat and implements ICatSounds. ICatSounds exposes MakeSoftPurr() and
MakeLoudPurr() and MakePlayfulMeow(). But, it also exposes MakeHiss()
and MakeLowGrowl() - both of which I don't need for my FriendlyCat class.
When I try to implement only some of the methods exposed by the interface
the compiler complains that the others (that I don't need) have not been
implemented.
Is the answer to this that I must create an interface that only contains
the methods that I want to expose? For example, from my CatSounds class, I
would create IFriendlyCatSounds? If this is true, then what happens when
I want to use the other methods in another situation? Do I need to create
another custom-tailored interface? This doesn't seem like good design to me.
It seems like I should be able to create an interface with all of the
relevant methods (ICatSounds) and then pick and choose which methods I
am using based on the implementation (FriendlyCat).
2) My second question is pretty basic but still a point of confusion for
me. When I implement the interface (using Shift + Alt + F10) I get the interface's
methods with "throw new NotImplementedException();" in the body. What
else do I need to be doing besides referencing the interface method that
I want to expose in my class? I am sure this is a big conceptual oops, but
similar to inheriting from a base class, I want to gain access to the methods
exposed by the interface wihtout adding to or changing them. What is the
compiler expecting me to implement?
-- EDIT --
I understand #1 now, thanks for your answers. But I still need further elaboration
on #2. My initial understanding was that an interface was a reflection of a the fully
designed methods of a given class. Is that wrong? So, if ICatSounds has
MakeSoftPurr() and MakeLoudPurr(), then both of those functions exist in
CatSounds and do what they imply. Then this:
public class FriendlyCat: Cat, ICatSounds
{
...
public void ICatSounds.MakeLoudPurr()
{
throw new NotImplementedException();
}
public void ICatSounds.MakeSoftPurr()
{
throw new NotImplementedException();
}
}
is really a reflection of of code that already exists so why am
I implementing anything? Why can't I do something like:
FriendlyCat fcat = new FriendlyCat();
fcat.MakeSoftPurr();
If the answer is, as I assume it will be, that the method has no
code and therefore will do nothing. Then, if I want these methods
to behave exactly as the methods in the class for which the interface
is named, what do I do?
Thanks again in advance...
An interface is a contract. You have to provide at least stubs for all of the methods. So designing a good interface is a balancing act between having lots of little interfaces (thus having to use several of them to get anything done), and having large, complex interfaces that you only use (or implement) parts of. There is no hard an fast rule for how to choose.
But you do need to keep in mind that once you ship your first version of the code, it becomes a lot more difficult to change your interfaces. It's best to think at least a little bit ahead when you design them.
As for implementation, it's pretty common to see code that stubs the methods that aren't written yet, and throws a NotImplemented exception. You don't really want to ship NotImplemented in most cases, but it's a good get around the problem of not having the code compile because you havn't implemented required parts of the interface yet.
There's at least one example in the framework of "deliberately" not implementing all of an interface's contract in a class: ReadOnlyCollection<T>
Since this class implements IList<T>, it has to have an "Insert" method, which makes no sense in a read-only collection.
The way Microsoft have implemented it is quite interesting. Firstly, they implement the method explicitly, something like this:
public class ReadOnlyCollection<T> : IList<T>
{
public void IList<T>.Insert(int index, T item)
{
throw new NotSupportedException();
}
/* ... rest of IList<T> implemented normally */
}
This means that users of ReadOnlyCollection<T> don't see the Insert method in intellisense - they would only see it if it were cast to IList<T> first.
Having to do this is really a hint that your interface hierarchy is a bit messed up and needs refactoring, but it's an option if you have no control over the interfaces (or need backwards compatibility, which is probably why MS decided to take this route in the framework).
You have to implement all the methods in your interface. Create two interfaces, IHappyCatSounds and IMeanCatSounds, split out those methods. Don't implement IMeanCatSounds in FriendlyCat, because a friendly cat is not a mean cat. You have to think about an interface as a contract. When you write the interface, you are guaranteeing that every class that implements the interface will have those members.
It throws a NotImplementedException because you haven't implemented it yet. The compiler is expecting you to implement the code that would be completed when the cat purrs, meows or hisses. An interface doesn't have code in it. It's simply nothing more than a contract for any class that implements it, so you can't really "access the code" the interface implements, because the interface doesn't implement any code. You implement the code when you inherit from the interface.
For example:
// this is the interface, or the "contract". It guarantees
// that anything that implements IMeowingCat will have a void
// that takes no parameters, named Meow.
public class IMeowingCat
{
void Meow();
}
// this class, which implements IMeowingCat is the "interface implementation".
// *You* write the code in here.
public class MeowingCat : IMeowingCat
{
public void Meow
{
Console.WriteLine("Meow. I'm hungry");
}
}
I'd strongly suggest picking up a copy of The Object Oriented Thought Process, and read it through in it's entirety. It's short, but it should help you to clear things up.
For starters, though, I'd read this and this.
Imagine that you could "pick and choose." For example, suppose you were allowed to not implement ICatSounds.MakeHiss() on FriendlyCat. Now what happens when a user of your classes writes the following code?
public ICatSounds GetCat()
{
return new FriendlyCat();
}
ICatSounds cat = GetCat();
cat.MakeHiss();
The compiler has to let this pass: after all, GetCat is returning an ICatSounds, it's being assigned to an ICatSounds variable and ICatSounds has a MakeHiss method. But what happens when the code runs? .NET finds itself calling a method that doesn't exist.
This would be bad if it were allowed to happen. So the compiler requires you to implement all the methods in the interface. Your implementation is allowed to throw exceptions, such as NotImplementedException or NotSupportedException, if you want to: but the methods have to exist; the runtime has to be able to at least call them, even if they blow up.
See also Liskov Substitution Principle. Basically, the idea is that if FriendlyCat is an ICatSounds, it has to be substitutable anywhere an ICatSounds is used. A FriendlyCat without a MakeHiss method is not substitutable because users of ICatSounds could use the MakeHiss method but users of FriendlyCat couldn't.
A few thoughts:
Interface Separation Principle. Interfaces should be as small as possible, and only contain things that cannot be separated. Since MakePlayfulMeow() and MakeHiss() are not intrinsically tied together, they should be on two separate interfaces.
You're running into a common problem with deep inheritance trees, especially of the type of inheritance that you're describing. Namely, there's commonly three objects that have three different behaviors in common, only none of them share the same set. So a Lion might Lick() and Roar(), a Cheetah might Meow() and Lick(), and an AlienCat might Roar() and Meow(). In this scenario, there's no clear inheritance hierarchy that makes sense. Because of situations like these, it often makes more sense to separate the behaviors into separate classes, and then create aggregates that combine the appropriate behaviors.
Consider whether that's the right design anyway. You normally don't tell a cat to purr, you do something to it that causes it to purr. So instead of MakePlayfulMeow() as a method on the cat, maybe it makes more sense to have a Show(Thing) method on the cat, and if the cat sees a Toy object, it can decide to emit an appropriate sound. In other words, instead of thinking of your program as manipulating objects, think of your program as a series of interactions between objects. In this type of design, interfaces often end up looking less like 'things that can be manipulated' and more like 'messages that an object can send'.
Consider something closer to a data-driven, discoverable approach rather than a more static approach. Instead of Cat.MakePlayfulMeow(), it might make more sense to have something like Cat.PerformAction(new PlayfulMeowAction()). This gives an easy way of having a more generic interface, which can still be discoverable (Cat.GetPossibleActions()), and helps solve some of the 'Lions can't purr' issues common in deep inheritance hierarchies.
Another way of looking at things is to not make interfaces necessarily match class definitions 1:1. Consider a class to define what something is, and an interface as something to describe its capabilities. So whether FriendlyCat should inherit from something is a reasonable question, but the interfaces it exposes should be a description of its capabilities. This is slightly different, but not totally incompatible, from the idea of 'interfaces as message declarations' that I suggested in the third point.

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.

Categories