adam bien's blog

Why Service Isn't A ServiceFacade, But ServiceFacade Is Sometimes A Service... 📎

You could design applications with Services only - no problem. You could even go with a single annotation @Stateless and combine your "Services" randomly:

@Stateless public class SomeService{

@EJB AnotherService service;

}

@Stateless public class AnotherService{}

It would even work consistently because of the EJB 3 defaulting. The first Service would start a transaction - all other will reuse it. The only problem are the fallacies of distributing computing and especially the granularity ("latency is zero"). Regardless, what platform or even programming language you are using, you should always be aware of the impact of distribution/remoting. 

The general solution is the introduction of a boundary, which main responsibilities are:

  • Providing coarser granularity
  • Ensuring consistency
  • Providing a defined entry point which can be easily decorated with aspects / interceptors
  • Exposure of components (what components are we will cover later) functionality to remote clients via IIOP, REST, SOAP, JMS, Hessian etc...

The manifestation of a boundary is the ServiceFacade - the facade to Services. The Services just rely on a certain amount of cross cutting aspects and concentrate on the realization of business logic. The ServiceFacade only invokes Services in consistent way, mostly using transactions. The Services can remain independent of each other - the ServiceFacade combines them. These are the typical responsibilities of a GoF Facade.

For simple use cases like CRUD, there is nothing to coordinate. If you would insist on layering, you will get a delegating (empty) ServiceFacade and an almost empty Service. For simple cases I just put the CRUD logic into the ServiceFacade - without having a dedicated Service. This violates the Separation of Concerns and Single Responsibility Principle and isn't elegant - but is pragmatic and lean. In worst case you can still extract the code into a Service afterwards. So sometimes a Service Facade can be a Service, but not vice versa...

I will cover ServiceFacade in more detail in upcoming posts. This is a highly condensed excerpt from my current book (see page 56 first edition / orange book, or page 83 second edition / green book and the Service pattern), a less condensed excerpt you will find at javaworld.com (Lean Service Architectures With Java EE 6)

I checked-in (pushed) the ServiceFacade in several variations into kenai.com.

I got many questions regarding the difference between a Service and a Service Facade. Hope its a bit clearer now.