Darrell Hawley: Home Page

Saturday, December 27, 2008

Note to Self 5 - Inherit and Override

I've been reading Working Effectively with Legacy Code by Michael C. Feathers. It's a trove of useful information for turning your unreadable and unreliable code into the complete opposite.

  • Here's a useful technique for dealing with dependencies that have problematic methods for testing. Mark the offending method as virtual and inherit from the class. Now you can use this new derivative class in your test methods in place of the original. Here's an example in C#.

    public class MyClass
    {
        public MyClass()
        {
            Console.WriteLine("MyClass has been initialized");
        }

        public virtual void DifficultMethod()
        {
            Console.WriteLine(
                    "Difficult method makes testing difficult.");
        }
    }

    public class MyClassDerived : MyClass
    {
        public MyClassDerived() : base()
        {
        }

        public override void DifficultMethod()
        {
            Console.WriteLine("It's testable!");
        }

    }

    public class ClassToTest
    {
        public ClassToTest(MyClass myclass)
        {
            Console.WriteLine("Initializing ClassToTest");
            myclass.DifficultMethod();
        }
    }


    The ClassToTest has a constructor that takes a MyClass parameter. Unfortunately, MyClass has the DifficultMethod which is a very...well, difficult method. By marking DifficultMethod as virtual we can override it in a derived class which can then be used to pass into the ClassToTest constructor. Handy.

  • Here's the same idea in Python

    class MyClass(object):
        def __init__(self):
            print "MyClass Initialized"
        def difficult_method(self):
            print "this makes things hard"

    class MyClassDerivative(MyClass):
        def __init__(self):
            MyClass.__init__(self)
        def difficult_method(self):
            print "MUCH better"

    class ClassToTest(object):
        def __init__(self, myClass):
            print "ClassToTest has been initialized"
            myClass.difficult_method()

Labels: , , ,

0 Comments:

Post a Comment

<< Home