Service s = new ServiceImpl() - Why You Are Doing That?

I see over and over again in projects and reviews the following "best practice":


Service service = new ServiceImpl();

Basically: for every interface there is an implementation with the "Impl" ending. That's not enough: sometimes both are configured in a XML-File (probably to emphasize the importance of this pattern :-)).

 

That is not only bloat (and the opposite of "Convention Over Configuration" idea), but it causes real damage:
  1. Imagine you get another implementation (thats the whole point of an interface) - how would you name it?
  2. It doubles the amount of artifacts - and significantly increases the "complexity"
  3. It is really funny to read the javadocs on the interface and the impl - another redundancy
  4. The navigation in the IDE is less fluent


I asked why developers are writing such code, but didn't got any reasonable answer, except "because of mocking".
This is, however, no more true for several years. Any ideas, why you are doing that?

See also: How To Deal With Interfaces In Java EE 6 (or no more Impl) 

Comments:

It might be because we have in our head very deeply an idea that says that we should always use interfaces to expose an API as this is the correct way to do it.

So when we are not able to give to the implementing class another "meaning" than being the implementation of the exposed interface, we put "Impl".

I've done this too. Honestly, after listening and reading you, speaking with other people and reading other books and articles, I fell silly looking my code developed in this way. :-)

Cheers

Posted by Katia on September 10, 2010 at 01:22 PM CEST #

@Katia,

we should propose a language at the JVM Language Summit: the name: "Interfacilitis".

The compiler would generate interfaces upfront to everything we are doing. Then everything would be replaceable, extensible ...and un-manageable :-)

thanks for your comment!,

adam

Posted by adam-bien.com on September 10, 2010 at 01:27 PM CEST #

Well, I can imagine more reasons. Such as:
* senior developer writes the interface of services(API) and some less experienced developer makes the actual implementation
* frontend guys might start to work as soon as the interface of backend is clear
* from various(valid or not) reasons you want/need to use JDK Proxying
* in big corporation you usually need to do tons of paperwork just to get a permission to use a new library(even for testing) - so Mockito might be out of game and you end-up doing your mocking manually (stupid reason, but it's reality in some organizations)

Posted by Jaromir on September 10, 2010 at 01:36 PM CEST #

Hi adam, I'm not so experienced in the JEE-world and don't get the point of your posting. What is the problem with Service service = new ServiceImpl();?

The fact, to name the implementing class "interfacename+impl" at the end? Better: Service service = new GimmeMoneyService();?

Or to use an interface as declaring type, which I've learned is good oo-style. Better: ServiceImpl serviceImpl = new ServiceImpl();?

Posted by Jo2r on September 10, 2010 at 01:47 PM CEST #

@Jaromir,

>>* senior developer writes the interface of services(API) and some less experienced developer makes the actual implementation

A bit of waterfall? :)

* frontend guys might start to work as soon as the interface of backend is clear

A good desire - but interfaces seem to change all the time.

* from various(valid or not) reasons you want/need to use JDK Proxying

A good point. I would always prefer dynamic proxy, over AOP.

* in big corporation you usually need to do tons of paperwork just to get a permission to use a new library(even for testing) - so Mockito might be out of game and you end-up doing your mocking manually (stupid reason, but it's reality in some organizations)

The other frameworks do provide class mocking as well. Btw. I didn't had any problem to introduce a testing framework in big cooperations - its just tests and it will not be deployed.

Thanks for your points!,

adam

Posted by adam-bien.com on September 10, 2010 at 01:50 PM CEST #

I would like to have more deeper explanations about this "anti pattern" and possible solutions for that problem.

Posted by jwi on September 10, 2010 at 02:01 PM CEST #

Well, I know it's possible to mock classes in several ways, but only if
* the class is not final and
* the mocked methods are not final either.
Now I have the problem that I use final very often within implementations for various reasons, so it becomes impossible to mock those objects/methods anymore.
And by using spring for example, I did not even have to know if there are other implementations or not. If I use a class instead I would limit the use of my Implementation in my eyes.
That's my reason to use interfaces even if I only have a single implementation for it at the moment.

Posted by Helge on September 10, 2010 at 02:07 PM CEST #

Hi Adam,

I know your comment for this point from one of your presentations in Berlin. (you remember the religious one at GameDuell :))

I think what is missing at your entry is, what is the proposed solution. How to do it better?
I think it's not just a JEE problem, because you will find it in a lot of libraries.

I'm tending often to have a Default..... which is an inner class. If I have ofter Implementations, I'm using speaking names which describes a little bit better, what they do.

So give us the way god would do it. :) (just a joke - but I'm interested in your proposal)

Posted by Daniel Manzke on September 10, 2010 at 02:14 PM CEST #

@Adam:
> A bit of waterfall? :)
Yeah, it smells like a waterfall, you're right. But I do not believe in the popular mantra: "Everything what has been polluted by waterfall is pure evil."

Designing good API is hard. And I find only natural that the hard parts are done by experienced people.

Posted by Jaromir on September 10, 2010 at 02:14 PM CEST #

@Jaromir,

nothing against interfaces. But I don't believe by interfaces designed by "senior" developers and implemented by "junior" guys. Often the juniors are better than seniors :-)

thanks!,

adam

Posted by adam-bien.com on September 10, 2010 at 02:18 PM CEST #

Just because interface can be used as a generic way to access a service while implementation (no need to always name it XxxImpl) is often a plugable implementation available in a separate component/package/jar.

Simple example are persistence mecanism or online services:
- high-level publish interface
- implementation for Flickr, Picasa, whatever...

Java is not limited to J2EE :-)

Posted by Sylvain on September 10, 2010 at 02:49 PM CEST #

If understand right you suggest not to use interfaces anymore with EJBs (~services) or what? Just pure class implementations?

Sorry, if I'm sounding stupid, but I'm just so "interface kind of guy" :)

Posted by jwi on September 10, 2010 at 02:53 PM CEST #

I always start with a single class and extract an interface when it becomes necessary (which is often never).

Valid points have been given in favor of interfaces (proxying, SPI). However, I don't agree with :

Mocking: as you've said, not more true for years. Even with final classes/methods: JDave provides a Java agent to deal with them (google jdave-unfinalizer-jar-name.jar). IIRC, it can be used with Mockito as well.

"Senior developer writes the contract / frontend-backend": you can do that with simple classes as well. What people often fail to realize is that you don't need an interface to express a contract: the visible API of a class does just that (this is explained very well in Effective Java). Just write the signatures and return dummy values.

Mocking framework not allowed: my experience is akin to Adam's, even my most rigid customers have been more lenient with stuff that wouldn't end up in production. Of course your mileage may vary.

Posted by Olivier on September 10, 2010 at 03:38 PM CEST #

@All,

will write a post about "Interfaces in Java EE" space soon. The "entry" editor is more convenient, than the comment one :-).

A general rule: if you cannot name the implementation after its responsibility and have to choose the Impl ending (or I prefix for an interface) - just get rid off the interface...

keep on commenting.

thanks!,

adam

Posted by adam-bien.com on September 10, 2010 at 05:02 PM CEST #

Half ACK. On the one hand I understand your point and in fact automatic interface-implementation code can produce useless code that needs to be maintained.

On the other hand there are two more points from me maybe worth to be considered:

1) "Composition over Inheritance" - Lots of us follow Josh Bloch's "Effective Java" book where he shows the beauty of composing new types using interfaces (instead of creating multilevel class hierarchies). *But* - this book is on API design and this principle wouldn't fit for every 'cheap' class.

2) Another reason might be designing for dependency injection (especially with Spring) if there is a least the chance that there will be several implementations of an interface. How would you address this matter using classes only? You had to extract an abstract class, then subclass and that's what most of us might want to avoid.

Regards,

Karsten

Posted by Karsten Gresch on September 10, 2010 at 08:49 PM CEST #

how about

ArrogantCondescendingJerkWhoJustLearnedANewToyTechniqueAndWantsToBashEveryoneNotUsingItOverTheHead x = new AdamBien();

Would that work for you?

Posted by Rance Moest on September 10, 2010 at 09:23 PM CEST #

@Rance,

agreed - as long it is not AdamBienImpl(). AND: the name of the interface is too long.

But you didn't answered my question... What is the reason to use ServiceImpl naming scheme?

Btw. I never (as long as I can remember) used that "pattern".

thanks for your semi-constructive comment!,

adam

Posted by adam-bien.com on September 10, 2010 at 10:34 PM CEST #

JEE Impl prefix could be avoid by putting the implementation on a package so you know thos are the implementation.

The best excuse to do this is Dependency Injection as @Karsten, and many EJB samples turn over that

Posted by Jose Ayerdis on September 11, 2010 at 12:11 AM CEST #

It's because interfaces aren't put in their own namespace.

There really isn't a good reason to not make the ServiceImpl accessible outside the package either so you would never see new ServiceImpl()

Posted by btilford on September 11, 2010 at 02:57 AM CEST #

What about layered architectures? In .Net for instance, I usually have different dlls, separating the layers, basically one dll containing all the interfaces of the business logic level classes and the other dll actually implementing those business logic interfaces.

My UI layer will then JUST depend on the interface and not on the actual implementation. This makes it easy to decouple, potentially to exchange the actual implementation classes without the need to go in the UI layer and change the non-compiling code there. And since the interfaces are already there, it comes in handy during unit testing too :)

Posted by Juri on September 11, 2010 at 11:43 PM CEST #

@Juri,

BUT: if there is always 1:1 mapping between the interface and the implementation, what the added value of the interface? It could be actually be generated from the implementation then.
...or replaced by a convention like: all public methods of a class do belong to "imaginary" interface.

thanks!,

adam

Posted by adam-bien.com on September 12, 2010 at 01:29 AM CEST #

Hi Adam,

Just on your first point, i.e. "Imagine you get another implementation (thats the whole point of an interface) - how would you name it?", another approach is to still use suffix Impl, but on different packages.

For example, for interface 'Service', you would have 'au.com.company.featureone.ServiceImpl' and 'au.com.company.featuretwo.ServiceImpl'.

I guess one of the advantages is that with this approach, all of the developers know that the convention used is the interface name + Impl. It'll be easier for searching, I suppose.

(I notice that Netbeans 6.9 will list the implementation classes and therefore making this point obsolete. Then again, not everyone uses Netbeans,... yet)

Posted by DWuysan on September 12, 2010 at 05:29 PM CEST #

@DWuysan,

if the package names are expressive enough - your approach may work. I prefer to name implementations after the responsibilities. A package provides a cohesive namespace for its elements.

thanks for your comment!,

adam

Posted by adam-bien.com on September 12, 2010 at 06:51 PM CEST #

I agree with adam if we are talking about the development of an application. Writing an application (even a subsystem of a bigger application) with extension in mind is useless and costly: these classes won't never be extended. It's also useless and costly to have interfaces for these classes, as these classes won't never be substituted.

Different the case of a library. The library writer needs to design for extension, and usually it provides an implementation of the library services which are also library extension points. For these default implementation for me is ok (not good, a more significant name could be better, but sometimes it's difficult for a generic class) to have Impl or DefaultImpl suffixes, or an implementation package.

Posted by Lucio Benfante on September 13, 2010 at 01:37 PM CEST #

@Lucio,

yes - absolutely.
I spend the majority of my time in application development. Library-development is comparable rare. Applications, however, are mostly developed in the "Library" fashion. It is "overengineering"

thanks!,

adam

Posted by adam-bien.com on September 13, 2010 at 01:42 PM CEST #

Just for better explain my previous comment. I think most of the comments to this article focused on the wrong thing.

It's not a problem of how to name a class. It a problem of how much time and effort you spend for designing and writing (and, of course, maintaining) the code of an application.

Posted by Lucio Benfante on September 13, 2010 at 03:05 PM CEST #

@Lucio,

"It's not a problem of how to name a class."

IMHO - you name a class after its responsibilities. "Impl" is redundant.

But you are also right - if the application is easy to maintain - who cares about naming...

thanks!,

adam

Posted by adam-bien.com on September 13, 2010 at 05:42 PM CEST #

Hi Adam,
I think that the concept behind that code is not a pattern but an OOD principle (the Open Closed principle in this case).

To get a good object oriented code you should always try to set dependency on abstractions of the classes and code the detail in the specific implementations, so sometimes you'll end up with something *similar* to the code you posted.

Obviously just creating an interface that wraps each class won't make your code more OO but is just boilerplate code if the coder doesn't understand why is doing that.

Programming to the interfaces works much better if you encapsulate the constructor of the service (in a factory for instance) separating the construction.

Having something like CreditCardService creditCardService = new MyBankCreditCardService(); will let you change the implementation in a second time.

Specifying CreditCardService service = CreditCardFactory.getInstance(); will allow the code to change the behavior (in this case the bank you want to connect to) without changing the code you've just written or at least putting all the changes in one place (the factory).

Posted by Gian Carlo Pace on September 13, 2010 at 06:04 PM CEST #

Why don't you name your interface IService and you implementation Service?

This way you can quickly recognize an interface with a single char (I) and you don't have ugly 'Impl' to write. :)

Posted by Bid on September 14, 2010 at 07:13 PM CEST #

@Bid,

I tried to clarify my point in this post: http://www.adam-bien.com/roller/abien/entry/how_to_deal_with_interfaces

You should be able to use interfaces without any naming conventions. If you cannot name the implementation properly, you should remove the interface and name the implementation after it.

it was a nice try with the I-prefix :-),

thanks you,

adam

Posted by adam-bien.com on September 15, 2010 at 05:31 PM CEST #

Hi All,

thanks for the comments! My view on "ServiceImpl":

http://www.adam-bien.com/roller/abien/entry/how_to_deal_with_interfaces

thanks!,

adam

Posted by adam-bien.com on September 18, 2010 at 05:46 PM CEST #

The necessity of defining interface for a service that is designed to have only one implementation is undoubtly an example of accidental complexity introduced by external factors (e.g. mocking platform). A set of public methods of a class implicitly defines its interface. If a type is designed to have only one implemenation ever, defining its interface explicitly is not essential for the application unless, unfortunately, the outside world expects it to exist.
For example if some implementation happens to be final, Mockito cannot mock such a class or method, and this is when an explicit interface has to be introduced. Also Spring or other platforms may demand explicit interfaces to exist in order to do their magic. However those reasons only uncover the outside world's imperfection, none of them confirms the ultimate need for explicitly defined interfaces. In other words, we write the interfaces because the tools we use, need them.
Imagine a world where mockito can mock final classes and DI platform can do without interfaces - there will be no longer any need for writing interfaces for services that are supposed to have only one implementation. Of course, the ones that are designed to have many implementations will be able to take all benefits of the 'interface and implementation' pattern.

On average how many implementations you provide per interface?

Posted by Marek Dec on October 05, 2010 at 03:20 PM CEST #

@Marek,

absolutely - cannot agree more.

thanks!,

adam

Posted by adam-bien.com on October 05, 2010 at 04:26 PM CEST #

The interface (not the keyword) has been around since procedural programming(a.k.a. API):
eg:
math.h and it's "Impl" math.c
But here we talk about the same function: it's prototype declaration(API) and it's implementation(compiled), not an interface and a class.

In OOP, the interface has two roles:
1. service/contract definition
2. (+)polymorphism

=> If we are talking #2 and good OO principles then "ServiceImpl" is NOT the right way because it is redundant and does not leave room for other implementations.
The right way would be:
eg: List: ArrayList, LinkedList
eg: Domain: IntegerInterval, DiscreteDomain
(No, interfaces must not have an "I" prefix or an "IF" suffix)
(No, implementing classes must not end with the interface name as they do not extend that type, but implement it + multiple interface implementations possible)

=> If we are talking about #1 then "ServiceImpl" is a good choice because we are using interfaces for service definition and implementation separation, not polymorphism.
eg:
In an Java EE app: a client project(or WAR module, client of the EJB module) will include and use only an API project (containing "Service")
The EJB project will import the API project and implement some/all of it's API. Hence, "ServiceImpl" will help make associations easier... it could even help in meta-programming (reflections)

Posted by CVictor on January 28, 2011 at 08:18 PM CET #

I smell "Speculative Generality".

for new developers i suggest they always program to interfaces, too get the practice of loose coupling, code flexibility, good coding practices etc...

experienced devs know when or not to use interfaces. interface per class is bloat.

Posted by perry on February 07, 2011 at 01:36 PM CET #

@Perry,

not entirely agreed. I would suggest for new developers to code against public methods and used interfaces to implement an "anti corruption" layer.

Coding against interfaces is best suitable for demotivated developers :-),

thanks,

adam

Posted by adam-bien.com on February 23, 2011 at 11:47 PM CET #

Adam,

Is this post specific to Java EE 6 apps? It seems to be, where you state, "It doubles the amount of artifacts...". But after skimming through some of the comments, it appears you are emphasizing also having an implementation-specific name rather than just an "Impl" suffix.

If this post is EE6-specific, I think you should put a note on this post saying so. If not, the part about doubling the # of artifacts doesn't really make sense, since <= EE5 we've had no choice.

BTW, I know you're other post http://www.adam-bien.com/roller/abien/entry/how_to_deal_with_interfaces is for EE6.

Thanks,
Ari
PS: as you can guess, my team is still stuck on EE5. ;-)

Posted by Ari on June 29, 2011 at 05:05 AM CEST #

@Ari,

this post is not Java EE 6 specific. In Java EE 6, however, all interfaces are particularly suspicious :-)

I'm working right now on a hybrid Java EE 6 / stand alone application. Without any interfaces...

thanks! Try to migrate to Java EE 6 and have fun deleting code :-)!

adam

Posted by Adam Bien on June 30, 2011 at 01:46 PM CEST #

Thanks, Adam, but then what do you mean by "doubles the amount of artifacts" in the context of EE5? We're still stuck writing an interface even if we only need a single impl.
Ari

Posted by Ari on July 01, 2011 at 04:22 AM CEST #

I remember that the EJB-Spec requires Interfaces for EJBs annotated with @Remote.

In our company all services are remote services. So we need Interfaces for every service :(

Posted by Jan on November 22, 2011 at 09:14 PM CET #

Hi,

No development activity should be systematic, us developers are not meant to blindly apply recipes but should rather use our intelligence to find the most appropriate solution to each situation (or maybe the one that is most likely to prove to be the most appropriate in the long, given an uncertain future).

I guess this is obvious (and hard), but while systematically creating one interface for each class is certainly not a good idea, systematically not doing so does not sound much better to me...

There are tons of interfaces I wrote which turned out to be unnecessary complexity, but for some of them I was very happy to be able to be able to replace the implementation (or part of it) with a new one, mostly when the new implementation is based on another technology (like migrating from AWS SDB to MongoDB) or to create composite objects that can chose which external object to delegate to depending on some condition.

Your example focus on the "service" layer. In a dynamic business we can encounter tons of situations where the business asks to do quick and dirty change to the core algorithm, maybe somehow temporary to test the market response to a new strategy. Those half-baked implementation can nicely fit in some wrapper intercepting calls to the previous implementation without adding ugly "ifs" in it. Now AOP offers some solution there, but sometimes plain old manual wrappers are just more readable to everybody.

Well, tons of situations can arise where the existence of a clean contractual interface between the client code and the service implementation provides a nice abstraction that does not cost much (IDE let us travel through all that easily), this is the whole idea of writing the service layer as an API that the boundary(ies) of application can rely on.

Posted by Svend on November 23, 2011 at 02:42 AM CET #

@Svend,

++1 !

Unfortunately: in the majority of all J2EE (even Java EE 5+) projects, interfaces are used just for "systematic development". I use interfaces for decoupling, algorithm encapsulation (strategy pattern), or public APIs. But then it is usually no problem to name the interfaces and implementations properly without the need to use strange naming conventions.

thank you very much for your comment!,

adam

Posted by Adam Bien on November 24, 2011 at 10:11 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License