How To Deal With Interfaces In Java EE 6 (or no more Impl) 📎
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.
@Stateless
@Local(CrudService.class)
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:
@Stateless
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:
- Strategy Pattern: there are already several implementations of an algorithm or concept
- Layering: there is a clear need to hide e.g. an ugly implementation of a legacy framework
- 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:
@Stateless
@Path("orders")
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.