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

DZone 's Guide to

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

· Java Zone ·
Free Resource

In EJB 3.0 interfaces were required. So whether you liked it or not, you had to provide one. To make it look a bit natural, you could remove the "Remote" or "Local" suffix. This naming convention was redundant, because the interface had to be directly or indirectly annotated with @Local or @Remote annotation.

public interface CrudService {


The name of the Session Bean ended with the "Bean" suffix. It was more a workaround, than a best practice. Whenever possible, I would name it after its responsibilities, e.g. JPACrudService.

public class CrudServiceBean implements CrudService {


In Java EE 6 interfaces became absolutely optional. Neither in EJB 3.1, nor CDI / JSR-330 you need interfaces. You can inject classes directly. They will be still proxied, so all aspects like persistence, transactions, interceptors, decorators are still available. So you are no more forced to implement interfaces by the container. In Java EE 6 the same example would like this:

public class CrudService {

For the consumer (the injection point) the implementation would look like the interface. In worst case you could still introduce an interface without any problems. In recent Java EE 6 projects we didn't used interfaces (they were actually forbidden) in general. They were used intentionally as a concept, not as a general rule. They were used for:

  1. Strategy Pattern: there are already several implementations of an algorithm or concept
  2. Layering: there is a clear need to hide e.g. an ugly implementation of a legacy framework
  3. API (not very common): you have to expose a API, which gets implemented by SPI (e.g. JDBC)

Even for decoupling purposes, interfaces are no more needed. You can expose an EJB 3.1 / CDI bean directly over SOAP, Hessian or REST without any interfaces:


public class OrdersResource {}

If you introduce interfaces intentionally - and not as a general rule, you will considerably reduce the number of files. Your code becomes easier to understand and so maintain. An interface will become an artifact to hide multiple implementations and not a general plumbing.

There are always exceptions from the rule. If your are building products, frameworks, containers or platforms the need for extensibility is greater, than in standard (enterprise) projects.

"Contract First", "Coding To Interfaces" or "Decoupling" is not a reason to introduce an interface for everything - its just a fancy term. The answer to the question like: "We have to decouple this legacy adapter, because..., so an interface is a good idea at this place" is a true explanation of a requirement.

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


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}