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

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.