If we assume that it is not desirable for the base class to be a pure interface class, and using the 2 examples from below, which is a better approach, using the abstract or virtual method class definition?
-
The advantage of "abstract" version is that it is probably looks cleaner and forces the derived class to give a hopefully meaningful implementation.
-
The advantage of the "virtual" version is that it can be easily pulled in by other modules and used for testing without adding a bunch of underlying framework like the abstract version requires.
Abstract Version:
public abstract class AbstractVersion
{
public abstract ReturnType Method1();
public abstract ReturnType Method2();
.
.
public abstract ReturnType MethodN();
//////////////////////////////////////////////
// Other class implementation stuff is here
//////////////////////////////////////////////
}
Virtual Version:
public class VirtualVersion
{
public virtual ReturnType Method1()
{
return ReturnType.NotImplemented;
}
public virtual ReturnType Method2()
{
return ReturnType.NotImplemented;
}
.
.
public virtual ReturnType MethodN()
{
return ReturnType.NotImplemented;
}
//////////////////////////////////////////////
// Other class implementation stuff is here
//////////////////////////////////////////////
}
Best Answer
My vote, if I were consuming your stuff, would be for the abstract methods. That goes along with "fail early." It may be a pain at declaration time to add all methods (though any decent refactoring tool will do this quickly), but at least I know what the problem is immediately and fix it. I'd rather that than be debugging 6 months and 12 people's worth of changes later to see why we're suddenly getting a not implemented exception.