0

In answer to this question Java Interfaces/Implementation naming convention author suggested

So when you have an situation where you have an Interface and a single Implementation that is not uniquely specialized from the Interface you probably don't need the Interface.

But what to do if you need to have interface for that single concrete class implementing interface so that you can:

  1. Code to interface
  2. Be able to mock object in unit tests

How to deal with this situation?

Community
  • 1
  • 1
gemasp
  • 59
  • 4
  • 2
    Well the author states `probably don't...` is not a rule. – gtgaxiola Mar 27 '15 at 14:20
  • mocking objects in unit tests doesn't require an interface. There are libraries which deal with objects (mockito etc). – Ria Mar 27 '15 at 14:24
  • "Code to interface" is a very misunderstood phrase. To me, it means creating interfaces when you need them, and not declaring your lists as "ArrayList myList", but using "List myList" instead, etc. It definitely doesn't mean creating a pointless interface for every single class, when you know there will only ever be one implementation. There's nothing worse than seeing "MyService" and a single "MyServiceImpl" - If you're calling it "*Impl", you don't need the interface... – David Lavender Mar 27 '15 at 14:32
  • If I am reading the OP correctly, he's asking the more general question of whether or not it's sensible to code an interface even when not *strictly* necessary. Unfortunately, the answer is a variant on "it depends", which I'm personally not a fan of, but we must make allowances for readability and future use. –  Mar 27 '15 at 14:33

1 Answers1

1

You answered it yourself with "But what to do if you need to have interface for "....

Once you need to have an interface (whatever the reason), then by definition, you need to have an interface.

  • By the way, it's not out of the question to code an interface just for clarity purposes (remember that in a professional environment, it's critically important for your code to be readable by another engineer later). Further, if you can conceivably imagine that down the road that your 1-off usage might someday become general purpose, then code up an interface. –  Mar 27 '15 at 14:28