Unit Testing – When to Use and Avoid the ‘new’ Keyword

testingunit testing

I watched a Google Tech Talk presentation on Unit Testing, given by Misko Hevery, and he said to avoid using the new keyword in business logic code.

I wrote a program, and I did end up using the new keyword here and there, but they were mostly for instantiating objects that hold data (ie, they didn't have any functions or methods).

I'm wondering, did I do something wrong when I used the new keyword for my program. And where can we break that 'rule'?

Best Answer

This is more guidance than hard-and-fast rule.

By using "new" in your production code, you are coupling your class with its collaborators. If someone wants to use some other collaborator, for example some kind of mock collaborator for unit testing, they can't – because the collaborator is created in your business logic.

Of course, someone needs to create these new objects, but this is often best left to one of two places: a dependency injection framework like Spring, or else in whichever class is instantiating your business logic class, injected through the constructor.

Of course, you can take this too far. If you want to return a new ArrayList, then you are probably OK – especially if this is going to be an immutable List.

The main question you should be asking yourself is "is the main responsibility of this bit of code to create objects of this type, or is this just an implementation detail I could reasonably move somewhere else?"

Related Topic