views:

79

answers:

3

I have several classes that conceptually belong to one tier. They have no common properties which is why they have no need to inherit from some base class.

I also have a few methods that deal with these classes. Some of them are templates of the following style:

public SomeClass
{
    public void SomeMethod<T> (T argument) where T : BaseClass
    {
        /* Do something */
    }
}

So I'm using this WHERE keyword just to secure the code (from myself I suppose), so that I don't by mistake feed to this method something else.

Naturally I made those other classes derive from BaseClass which is empty and has no other purpose (at least for now) than to group other classes.

This is probably not that good approach but anyway I'm using it.

Is there a better way to do this?

EDIT: After consideration I decided not to go with that approach and just removed that base class. Good enough without it. I cannot make the code absolutely perfect anyway, and the less unneeded thing there are the better.

+5  A: 

Use a marker (empty) interface instead of a base class:

public void SomeMethod<T> (T argument) where T : ISomeInterface
A: 

Perhaps a more concrete example would provide a little more perspective. As it stands, I'd say you should not group classes in this way.

Your SomeMethod() method obviously does not reference any of the properties of the argument (or if it does, it also must be casting the argument to different type(s)); What is the reason for securing the code "from yourself"? What would happen if you were to call the method passing in an object that was not approved?

If the argument constraint is absolutely necessary, I would recommend as Grybyx did, use an Interface. That'll save you from issues with multiple inheritance.

Chris Shaffer
+1  A: 

+1 on Jeff's answer. Tagging ("marker") interfaces are common in both C# and Java frameworks. They let you assign a common type to "class A" so that another class ("class B") can be ignorant of class A's concrete type.

As with anything this flexible, it's easy to misuse, but in your case it definitely fills the bill.

pluckyglen