tags:

views:

86

answers:

6

I have an interface called ICommand from which various classes inherit. These classes all do various different things with the Run() method, but they all need to have a Name property and a Description property that specifies what they do.

The question is, how should I let each subclass specify those properties (Name and Description). At the moment I have put a property for both in ICommand and I get each subclass to implement those properties and just have a return "Blah Blah Blah" statement in them. Is this the best way to do it? Or should it be done another way?

Sorry if this seems like a silly question - I'm just starting with this OOP design stuff and I want to check I'm doing it right.

+1  A: 

I think, defining a Readonly Property in the interface is the best way.

Sebastian Sedlak
A: 

This is typically the approach I take. I find that requiring subclasses to override a virtual property or method to return a descriptive identifier is fairly easy and fast. I imagine that you could do something similar using reflection, but you will certainly take a performance hit.

Matt Jordan
A: 

Classes are said to implement an interface, not inherit from it as interface don't have an implementation (and thus nothing to inherit). You can certainly do what you're doing, and if the Name and Description properties are unique to all your type, you'll end up with multiple implementations. Nothing wrong with that if I understand you correctly.

Brian Rasmussen
+1  A: 

I have written something similar (plugins) where each class has a different name and description and ended up implementing as Sebastian says, with a ReadOnly property

interface ICommand {
string Name { get; }
string Description { get; }
...

classSpecific : ICommand {
public string Name { get { return "Specific"; }}
public string Description { get { return "Specific description"; }}
...
BlackTigerX
A: 

You are on the right path. What you are describing is similar to the Strategy Pattern where you have several classes that implement an interface (either an actual interface or an abstract class) then have their own implementations for the methods.

DavGarcia
A: 

If the Name and Description property are different for each implementing class, then by all means, do what you're doing. Force every class to implement those properties (through your interface) and let them provide the details. If however, the Name and Description can be the same for many of the classes (although with name and description it probably won't happen) then your other alternative would be an abstract class where Run() is an abstract method, and Name and Description are virtual properties.

BFree