Monday, February 4, 2013

Declaring Instances as Fields in Interfaces is a Testability Problem

Typically, when you see fields defined in Java interfaces, they are things you would normally think of as "constants" -- e.g. int's, Strings, maybe an enum or two. I had never really thought much about the fact that you can have instances of more complex classes as interface fields until I actually saw it in practice. Something like this:

public interface MyInterface {
  // Singleton instance.
  MyInterfaceImpl INSTANCE = new MyInterfaceImpl();
  // Interface methods...
  void doSomething();

Then you can use that field like a static variable, most likely as an old-school (pre-dependency-injection) singleton instance.

There are two problems with this as far as testability is concerned. First, you have the usual difficulty you get with static instances in unit tests, namely, that you cannot insert a mock, stub, or fake in all of the places where it is referenced. But if that is not enough to convince you to not use this pattern (hint: it should be), there is another problem that is arguably even more insidious.

Let's say that by some stroke of luck, you are trying to test a class that does not make static reference to the singleton instance and accepts the dependency properly. Now, when you go to create a mock or fake implementation of MyInterface for use in the test, Java still has to instantiate MyInterfaceImpl at classload-time. Depending on what all that involves, this may be expensive, unstable, or flat-out fail in the test environment, thereby thwarting your efforts to properly unit-test.

Obviously, the easiest way to solve this problem is to avoid it in the first place. But if you happen to run into it in a legacy system, you can start migrating away from it gradually by simply moving the instance to another class, or by using something like the value-holder pattern or initialization-on-demand holder idiom that moves the creation of the instance out of the classload sequence for the interface.


jaffa said...

It is very good content and useful information. I love this blog page. I read this content is very interesting and truthful info. So I am remember your blog to my further doubts. Thanks for sharing good article in your blog page.

social marketplace

Jessi Gianni said...

Great post, thanks for providing this information.

we buy junk cars orlando

Mohita Gupta said...

Looking for a software company needs an assessment of the experience levels and expertise that they have in the domain of software development.A reliable and reputable software development company in Jaipur is to interact with the clients from time to time and every change.

jowdjbrown said...

There’s quite a bit of truth to what Mark is saying about startup software developers, but my guess is that there’s another reason that it seems harder to find developers in this context.outsourcing developers in Ukraine