top | item 8773327

(no title)

rverghes | 11 years ago

He's assuming that the static method has a dependency on something. That it's not purely functional. For example,

  public static doSomething() {
    Database.write("Did something")
  }
Makes testing hard because Database is hardcoded.

discuss

order

pbh101|11 years ago

You put it well, and most people in this thread (including GP) seem in violent agreement.

In short: static methods are easy to test, methods using static methods (whether static or not) are more difficult to test.

My takeaway: the bar for moving functionality into non-static methods (which will still be decently easy to test) is quite low. If you call a static method, be prepared to own all its functionality when testing the calling method. Taken to logical conclusion, public static methods should be quite small.

_asummers|11 years ago

Additionally, if you need to mock that doSomething() method's behavior at all, you can't just subclass and override the method. You would need to bring in byte code voodoo (using e.g. PowerMock in Java).

blktiger|11 years ago

And PowerMock is the bane of all existence!

It can be a useful tool, but it causes all kinds of weirdness which can completely mitigate any advantages. On my current project I had to strip out most of our uses of PowerMock. While the tests pass on my local machine just fine, many of them fail for no good reason on the CI server.

judk|11 years ago

Fake, not Mock (if you need to Mock, you've alrrady lost), but yes, you shouldn't write anything static if you'll need to provide an alterate implementation of the interface.

bglazer|11 years ago

So would a better solution be to use something like:

    public static doSomething(Database db){
        db.write("did something"
    }

rverghes|11 years ago

Not really, because db is not static. In my example, that Database.write() method would itself be static, and thus you can't pass it in as an argument.

Basically, this concept means that it's static all the way down, from the top layer to the bottom layer.