Search This Blog

Loading...

Monday, October 13, 2008

Static Method, Is It that Harmful?

Static method is much more easier to learn, and use compare to OOP and polymorphism,. But somehow it acquires a bad name in the TDD circles. Some people don't like static methods . The reason? Can't mock the static methods.

I agree that mocking is good , and sure, I do use a lot of mocking in my code . but the very inability to mock something shouldn't be the reason to reject it. For starters, static method does have a lot of virtues. It is clean, for the inputs and outputs are plain visible just from the method signatures. You don't have to guess what are the other inputs that are required by that method. All the inputs are available as the method parameters, and all the outputs are available as the return values ( or the ref or out parameters). The same cannot be said of OOP and polymorphism. You can inherit a class, invoke a method inside the class and get a NullReferenceException  simply because you forget to set one of the crucial variable that is required for the method to work successfully. In this sense static method is actually easier to understand and easier to work with.

Not only that, sometimes using static method is more natural than using inheritance and all that is related to the fanciful OOP. I can't think of an example on the fly now but I am sure you will agree with me on this point because you have encountered this kind of situation before.

Now, coming back to the issue of mocking. Some mocking frameworks can't mock static method, because in the process of mocking they are actually subclassing the mocked class and fill in all the fake values and pretend that this is mocking. Personally I have nothing against this technique. As long as it works, who cares. But the trouble is no one can override a static method. And so, no mocking for static method. Since we know mocking is good, hence static method is bad.

Instead of dismissing static method out of hand, why not just take the other approach? Why not just improve the mocking framework so that it can handle static method? Instead of dynamically subclassing mocked class, why not just use AOP to intercept the method calls and do all the mocking you want (This is how TypeMock  does the mocking)? In this way you can mock classes and objects, and you can mock static methods, too. Isn't that simply great?

Banning static method--even though it is perfectly sound and can improve readability-- simply because the mocking frameworks can't handle it seems to me like fixing the symptom rather than the root cause. And yes, the "fix" is going to bring another set of trouble and chaos.

Is it worth it? I doubt.