Wednesday, September 10, 2008

Worst usage of virtual Members ever

Disclaimer: This code has nothing to do with my current projects and was refactored immediately!Imagine you find a base-Class somewhere in your code which has about 4000 lines of code: first you'll sit down, drink a coffee and than try to find out what went wrong here ;)

Let's shorten this monster class a little bit to a readable snippet:
public class VirtualDoNot
{
public VirtualDoNot()
{
IsTest = false;
}

public virtual bool IsTest { get; set;}

public void WriteSomeStuff(string stuff)
{
switch(IsTest)
{
case(true): DoSomething(stuff); break;
case(false): DoSomethingElse(stuff); break;
}
}

private void DoSomething(string stuff)
{
//Action here
}

private void DoSomethingElse(string stuff)
{
//Action here
}
}
Now imagine this snippet spread over 4000 lines in the same manner and try to think of the derived classes.For those of you, who can already imagine what happened: YES, they really did it!!!
public class Inheritor : VirtualDoNot
{
public Inheritor()
{
IsTest = true;
}

public override bool IsTest { get; set;}
}
And here an example of the usage:
public class Worker
{
public static DoWork(string stuff)
{
Inheritor inh = new Inheritor();
inh.WriteSomeStuff(stuff);
}
}
Conclusion: if you use virtual Members, be sure you know what inheritance is all about and do not abuse them as switches for a giant base class!

No comments:

Post a Comment