My recent post inpired a friend of mine to write about the untestability of the code. Go check the entry before reading further, because it a response.

Though I do agree with his general point - code that is hard to test probably is a bad code and should be refactored - I don't agree with the claim that static methods are pure evil.

First, static methods are a part of the language and are very useful at times. Replacing them blindly with, say, dependency injection would be a classic example of overengineering a problem. It's just not worth it. Static method is a very simple solution to a very simple problem. It can be overused, as any element of the language, but using it is not a bad design all by itself.

Second, I tend to treat developers as responsible grown-up people (as long as programming, and only programming is concerned, of course). I want them (and me) to have all the tools and means necessary to shoot their own foot should they wish so. I'd rather have tools I could accidentaly hurt myself with - like with a lot of work to implement a change later in the lifecycle of a piece of software - then having the tools that would limit me in my job. That's why I prefer Python to Java. And I think that's the reason Java evolves towards giving developers more control over what they can do with the language. In other words, thank you Mr Language Designer, I know how to handle a gun, you don't have to limit me in my desire to point it to my foot.

And third - I cannot just call somebody at Sun and say: "Listen up, I don't like that System.getEnv is static. You'd better make it a real method in Java 7, 'cuz you're making my code hard to test." I actually like that method being static. I think it should be static. It's the right usage of a static method. The same can be said about lots of other methods and other libraries. And I found a simple way to test code that uses them.


Comments

1 Comment so far

  1. guilty of untestability - intro :) « monkey island on December 29, 2007 9:02 pm

    […] Stuff like utility libraries - they’re fine and I’ve never needed to mock them. Tomo defends static methods bravely. He is right but mocking static methods still smells funny… If the […]

Name (required)

Email (required)

Website

Speak your mind