Wednesday, August 19, 2009

Don't Arbitrarily Reference the Base Class

 

All too often I have seen developers referencing properties and methods of the base class directly. Instead of calling “this.SomePropertyOrMethod()” or just “SomePropertyOrMethod()” they call “base.SomePropertyOrMethod()”. This has a number of drawbacks.

1) It implies that a class knows something specific about the parent.

2) It is now difficult to override the method in this class or a class that inherits from the current class. The base version of the method will always be called even if the method is overridden.

3) This defeats the purpose of object oriented programming. Calling the base class directly is akin to calling the same method on a utility class. The only difference is that the base class might be looking at the current class’s state. It’s just messy.

4) This is a code smell that makes me think of the Base Bean anti-pattern. “A class should not inherit from another class simply because the parent class contains functionality needed in the subclass.”

Now there are definitely times when this is necessary and that is why the keyword exists in the first place. If I’m overriding Page.OnLoad, I should call base.OnLoad at some point. If I override List<>.Add, I better call base.Add() to add the item to the list.

But just because you can do something doesn’t mean that you should. And this keyword is no different. Most cases of base.SomePropertyOrMethod() should be replaced with this.SomePropertyOrMethod().

1 comment:

  1. I had to test this myself before I believed it...
    abstract class SuperBase
    {
        public virtual string Name
        {
            get
            {
                return "Blue";
            }
        }
    }

    class PainInTheBase : SuperBase
    {
        public void Do()
        {
            Console.WriteLine(base.Name);
        }
    }

    class Renamer : PainInTheBase
    {
        public override string Name
        {
            get
            {
                return "Green";
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Renamer r = new Renamer();
            r.Do();
            Console.ReadKey(true);
        }
    }

    the program will output Blue!
    It makes total sense but... Ouch! This is a really bad habit to get into doing.

    ReplyDelete