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 comments

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.