Overload Static Methods Inheritance: A Bug Story
Today I had a bug, a very nasty one. This bug was quite innocent, is looked like this:
A pretty simple code, isn't it? The Black() method is a static method that just creates the object (its purpose is to simplify instansiating the object, nothing more). But instead of getting a poodle, I was getting a generic dog!
The sad part about it is that it worked when I was trying to save it, and only bombed when I tried to load it, meaning that I got the exception on a totally unrelated place in my code. After indiscrimantely accusing (roughly in this order):
- Castle.ActiveRecord
- NHibernate
- Sql Server
- TCP Stack
- The Cat
- The Little Green Men
- That Guy Over There
I sat down and really looked at at, and I still couldn't find a reason that this would give the end result. The Poodle class obviously had a static Black() method, in which a Poodle was created and returned. Why was I having this problem? What did I do to deserve this?
Well, I did something very stupid, let's see if you can figure this out from the code:
public class Dog : Animal
{
public static Dog Black(string name)
{
return new Dog(name, Color.Black);
}
}
public class Poodle : Dog
{
public new static Poodle Black(string name, bool isNasty)
{
return new Poodle(name, isNasty, Color.Black);
}
}
Do you see the problem? I was using the wrong overload, and the method that the compiler called was Dog.Black(). Finding out that it was my fault didn't go very well with the Cat, I can tell you that.
Anyway, the lesson is that you should be careful about "overriding" static methods, because they can bite.
Comments
Comment preview