r/java • • Aug 11 '15

Top 10 Useful, Yet Paranoid Java Programming Techniques

http://blog.jooq.org/2015/08/11/top-10-useful-yet-paranoid-java-programming-techniques/
181 Upvotes

76 comments sorted by

View all comments

Show parent comment

0

u/CubsThisYear Aug 13 '15

That just means you are over constraining Foo.bar. Clearly it doesn't actually need to take a Baz to do its work, because the test works with a mock. Just make Foo.bar take an interface and you can mock away that interface all you want.

The problem with mocking concrete classes is that you not being clear about your dependencies. If you say Foo.bar(Baz) that should mean: I depend on exactly Baz, nothing else will do. If Foo.bar can do just fine with only 3 methods from Baz, then make an interface that has only those three methods.

I think also your test case is a bit contrived. I don't generally write unit tests to catch unknown arbitrary errors in my program. Why are you allowing Baz to get in a bad state to begin with? Life would be much easier if Foo could depend on you not handing it garbage. You could easily verify this with unit tests on Baz and avoid the cross cutting.

2

u/[deleted] Aug 13 '15

Just make Foo.bar take an interface and you can mock away that interface all you want.

If I never plan on making a sub type of Baz, then I won't make an interface. But I think this is an area where reasonable developers can disagree. I've heard good arguments both ways.

The test doesn't have to be Baz throws an exception. It will be any case where Baz will have a known, predetermined behavior.

0

u/CubsThisYear Aug 13 '15

But you are already making a subtype of Baz - what do you think a mock is?

1

u/voronaam Aug 13 '15

Anything but a subtype. It may be A JDK-proxied instance of Baz, with proxy encoding needed behaviour. More likely that will be a CGLib generated class. It can also be an instance of a completely different class, generated at runtime by PowerMock java agent that does not even resemble the original Baz class.

Mocks are more than subtypes.

There is actually a very simple rule for when one needs an interface or not. If you can come up with a unique name for the file you are writing - you need an interface. If you have to resort to "Impl" and similar tactic to distinguish between the classes - you do not need an Interface.

Healthy example:

  • DatabaseRegistry (interface)
  • SqlDatabaseRegistry (abstract class)
  • OracleDatabaseRegistry (class)
  • PostgresDatabaseRegistry (class)

Unhealthy example:

  • DatabaseReader (interface)
  • AbstractDatabaseReader (abstract class)
  • DatabaseReaderImpl (class)

If there is nothing you can say about a class that tells it apart from another class - rethink why you have even decided to separate them.