The more I read, the more confused I am.
Note that all the question is related to how service and facades fit on the MVC pattern.
My understanding is that a Facade is not a super-smart object, it is simply a way of exposing a simple interface/api to perform a complex operation (example: perform a 10$ payment, it is a complex operation that involves a number of operations, but such complexity can be handled by a facade which will just call the corresponding object in a particular order...etc...)
Now, a service is a way to perform calls to several DAOs in order to get complex data structures (I am not too sure of this, but it is what I understand so far).
Question then is, what is the difference between a facade and a service? At the end of the day, the facade can perfectly access several DAOs in order to perform a complex operation by providing a simple interface, and a service seems to to something similar.
Same happens with transactions, I understand that a service is the place to start transactions, but I equally feel that they could also be placed on facades, after all, a facade may call several DAOs too.
So which stack would make more sense
controller-facade-dao
controller-service-dao
or maybe
controller-facadade-dao AND sometimes controller-facade-service-dao ??
A service is a way of writing an interface to an external system, such as a LDAP identity store, a payment gateway or an application management interface. It's a conceptual way of looking at the external system as a provider of useful services perhaps with internal behaviours rather than a passive lump to be operated upon.
A facade is a way of wrapping up anything (including a service) to present it nicely to another component. Facades are often used when:
A library or component is complex and your application needs only a subset of it. Your Facade presents the simplified API to the application
You are using several libraries or components and need to unify them, presenting a consolidated API to the application
The library you are using has a complex setup or set of dependencies, and the facade wraps all that up in the context of your application.
The bit that is really confusing is that you can (and often do) create a facade over one or more services. The service is the way that the component actually accesses the resource, and the facade is the bit which simplifies the component (such as configuration of options, connecting, etc).
If you write your own DAO, you probably will create your service just how you need, so writing a facade is an indication you did it wrong. If the DAO is built by a third party, and is more complex than your needs, then you can facade the service.
Now, a service is a way to perform calls to several DAOs in order to get complex data structures (I am not too sure of this, but is is what I understand so far).
I would say that the DAO is a design pattern all its own - see wikipedia.
If we contrast a DAO with a service, we have:
Level of API:
DAO: Fine-grained access to properties
Service: Coarse-grained access to services
Where implementation lies:
DAO: Mainly on the client, but storing data (without behavior) in the database
Service: Mainly on the server
How the interface is invoked
DAO: The client directly binds to the object in the same namespace and JVM
Service: The client is simply a stub for a network, cross-vm or cross-namespace operation
... the facade can perfectly access several DAOs in order to perform a complex operation by providing a simple interface, and a service seems to to something similar.
A facade could wrap up the DAO layer, but I don't really see this happening in a useful way. Most likely you need an API to access the individual properties of the objects, traverse the object graph and similar, and that is precisely what the DAO provides.
Same happens with transactions, I understand that a service is the place to start transactions ...
Absolutely, because the transaction is a service provided by the database and on another component or system
... but I equally feel that they could also be placed on facades, after all, a facade may call several DAOs too.
And in many ways the transaction manager service is a facade onto a much more complex backend implementation, co-ordinating the transaction on the web, application, database and other transaction-aware components. However this is already abstracted away by the transaction service implementation. As far as we, the user, are concerned, there is only the public interface.
This is, in fact, the conceptual point of these design patterns - to provide just the right amount of API to the user, abstracting the complexities of the implementation behind the iron wall of the component interface.
So which stack would make more sense
controller-facade-dao controller-service-dao
or maybe
controller-facadade-dao AND sometimes controller-facade-service-dao ??
The DAO is a kind of service to the database, but really the DAO is a design pattern itself.
If you write your own DAO, you should never need a facade.
Therefore the correct answer is:
controller - dao
Literally, Facade as the name suggests means the front face of the building. The people walking past the road can only see the facade, They do not know anything about what inside it, wiring, the pipes and other complexities. The face hides all the complexities of the building and displays a simpler friendly face.
In software terms, facade hides the complexities of software components behind it by providing a simpler interface, doesn't have the functionality of its own and doesn't restrict the access to the substsyem. Commonly used in Object Oriented Design.
Good examples are SLF4J - It is an api which is a simple facade for logging systems allowing the end-user to plug-in the desired logging system at deployment time.
A service is a public interface that provides access to a unit of functionality and always written to a specification. It needs to support the communication contracts (message-based communication, formats, protocols, security, exceptions, and so on) its different consumers require.
There is process services - encapsulation of business workflows , business logic service - encapsulation of rules/functions, data services - interaction with entities, data access management, infrastructure services- utility functions such as monitoring, logging & security. Services are mostly reusable, unassociated, loosely coupled units of functionality.
They are lot similar but depends on how you look at it.
The difference that I see, Facades are designed inside out. You look
at subsystem and design a facade to provide simpler access. Services
are designed outside in. You look at your customer/clients define a
contract and design the service.
My understanding of the classical GoF Facade pattern is that it's mainly intended to hide a poor design. As a rule of thumb, I would say that one should only need a Facade for legacy code.
I also think that this pattern made its way as a J2EE core pattern (Session Facade) mainly because the EJB spec (at least up to 2.x) inherently resulted in a poor service layer design.
Therefore, my answer to your question would be yes -- a facade is actually a service that hasn't been properly implemented the first time. If you need to hide the complexity from client code, it usually means that you only managed to provide a library, not a service layer; so, in this case, the Facade actually becomes your service layer.
On the other hand (assuming you have a decent domain layer), if you really need to provide the option of spawning complex flows with a single method call (something resembling macros/aliases), this would usually be better placed in the application layer and not in your core domain -- notice that I've switched layering terminology to domain driven design, where there's no "data access" or "service" layer, but "application", "domain", "infrastructure".
The first thing to note is that a design pattern is a description for a common (design) problem with a standard solution. In some cases there are several ways to solve the problem in a way that fits all requirements (f.ex. the Iterator and Singleton patterns have tons of different implementations; f.ex. check the work of Alexandrescu and compare it with the standard GoF solutions) and in some cases there are different patterns with the same (code) solution (f.ex. compare the class diagrams of the Composite and the Decorator patterns in the GoF book).
According to the GoF the purpose of the Facade pattern is to (literal quote):
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easier to use.
Services have the intention of providing a user with a single higher level interface with a given functionality. That doesn't necessarily make it a facade, because a service is strictly speaking not by definition a unified interface to a set of interfaces in a subsystem.
But we can do better than that
Your question was if the patterns are "similar". If we consider them to be "similar" when pattern A equals B and pattern B equals A, then we should answer 2 questions:
Question 1: is a Service a Facade? A service should definitely expose functionality and is definitely a single interface that exposes this functionality. Functionality is normally decomposed into tiny pieces, so yes, services fit the underlying requirements of a facade. In other words: faced by the problem of exposing the underlying interfaces as a unified "service" interface, the facade pattern fits the requirements and is used to solve the service problem. The answer to this is yes.
Question 2: is a Facade a Service? Services are normally designed as reusable, unassociated, loosely coupled units of functionality. Thinking about communication between components is important for services, because they usually rely on a TCP/IP interface such as SOAP or WCF. This also means that functionality is often rewritten to fit the services paradigm more closely, which adds an implicit driven by performance requirement for the pattern. Facades don't have this extra requirement. In other words: a facade is not a service.
In exact terms, these concepts are closely related, but not the same.
But we can do better
This line of thinking raises the question if a service is an extended version of a facade? It is if a service meets all the requirements of a facade and extends on top of that.
If you read the description by the GoF closely, the answer is yes, that is: if one condition is met: The service has to expose subsystems. In reality, I think this condition normally holds, or you're over-designing your services - though strictly speaking I suppose this is not a hard restriction.
FACADE is a design pattern which solves the problem where there is a need for a unified interface to many interfaces in a subsystem so it defines a higher-level interface that makes the subsystem easier to use.
HOWEVER, A SERVICE provides access to resources or a set of interfaces/objects and may not necessarily simplify such an access. So you can employ the facade pattern to better design your service so you can save the client figuring out how to construct to use it.
Usually these terms are just used in their specific contexts.
'Facade' common usage context: simple API for complex parts of the application (like third-party libs)
'Services' context: unlock and surface the business entities in the system. (SOA, DAO, Security, etc)
You can view patterns as a language that evolves. It never seemed to be perfect end each pattern has it's own history and context. Sometimes classes could be viewed as Services and Facades at the same time, sometimes not.
For example: calling third party API by term 'Service' could be considered as misuse, because of the wrong context.
Before I try to answer, let me clarify something: there are three distinct things in enterprise applications - Facade, Service Layer, and Remote Facade.
Facade - while wrapping the subsystem(s), still is an object and UI (MVC) application usually lives in the same process. Thus, the communication is done in an usual OO manner: calling methods, reading properties, listening to the events.
Service Layer - when the business logic layer becomes mature and too complex for the MVC to interact with it directly, then Service Layer is put between them. Service Layer is an API that MVC uses as a wrapper of the business logic. It is not remote and is not required to use DTO since no wire is involved in the communication.
Remote Facade - (simply, any remote service) this is a hybrid of the Facade and Service Layer. Remote Facade starts existing when you want to expose some kind of wrapper over the system (and we call it Facade) as a distribution boundary. One of the reasons can be to allow several UI (MVC) applications use the same Remote Facade.
-
Comparisons:
Facade vs. Service Layer: they are similar since both they wrap subsystems. Difference is that Service Layer is more oriented on UI (MVC) application needs and exposes functions to simplify working with business logic. On the other hand, Facade is exposing functionality to simplify the business logic, but does not necessarily simplify the communication with UI (MVC) application.
Facade vs. Remote Facade (Service?): definitely different since Remote Facade must use DTOs as communication messages. Remote Facade will need some kind of proxy if you still want to use it as a regular object (properties, events); but the proxy will anyway use DTOs to the real object, i.e. Remote Facade.
-
Possible Flows:
controller-facade-dao - doubtful, but still possible. Facade is not usually used to wrap just DAL. There should be something more mature in addition as a subsystem. But, if the facade is part of the business logic, then yes, this is possible. Still the subsystem must be more emphasized. To me, DAL wrapping is not enough to call it Facade.
controller-service-dao - absolutely possible. Many remote services work directly with database through DAL.
controller-facade-service-dao - maybe, if you treat service as a subsystem.
I would add one more that can make sense:
controller-service [layer]-facade (part of business)-subsystem (e.g. accounting, business on its own)-dao - I'm sure you can translate this.
-
Remember, Service (or remote facade) can exist anywhere in the flow. That is just dictated by your distribution needs.
A service interface typically represents business concerns: perform some operation(s) and/or get some information. It wouldn't be unreasonable for the service provider to implement their service as a facade over internal back-end services - you'd never see this.
Your facade might wrap some general interfaces, which might include service interface(s).
For example, you might have service interface for a bank account (operation: Bank transfers money), and a local API to your local accounting records (I transfer money). You might introduce a facade over with a "move money" operation that uses the bank's service interface and manages your local checkbook as well.
It is the "context" that's matters. Facade and Service are not conflicting.
First I have never heard of "Service" and "Facade" in the context of MVC.
When people talk about Service, it is more about a system or component providing business-meaningful actions to outside world. You may sometimes see "Service" related to "Unit-of-work" (and hence, transaction).
Service is also used in the context of some layering approach of application: we have Service on top of DAO, for which Service will access data through DAO and business logic is put in Service layer, something like that.
Facade is usually used in the context of design pattern, and the focus is about "hiding complicated operations and expose it as a simple operation".
Facade may be or may not be a Service (a operation in Facade may not represent a Unit of work, but it is still a valid facade), similarly, a Service may or may not be a Facade (a Service may not hide any complicated operations but it is still a Service).
Again, it is all about the "context" that matters.
For example, when you are talking about layering of application, it is simply irrational to say "XXX is a facade to access DAO". Similarly, if you are talking about "design approach", it is more reasonable to say "XXX is a facade to multiple back-end" instead calling it a "Service" here (Although XXX is actually a Service).
Yeah, Facade and Service are not entirely unrelated. And some time we implement Service layer as Facade so that client is not bothered about to many details of the service. The more simpler the invocation/interface of a service is the simpler and easier clients code.
The Martin Fowler says...
A Service Layer defines an application's boundary [Cockburn PloP] and its set of available operations from the perspective of interfacing client layers. It encapsulates the application's business logic, controlling transactions and coordinating responses in the implementation of its operations
So services layer is used at times as Facade.
Ref
Facade and Service Layer has kind of a similarity but both of them has two distinguished meanings. Let me explain this using a simple example.
Imagine we are asked to create new business application. This has a requirement of creating a check-in application but with more value added features and loyalty card features.
Lets say application should support Facebook and Foursquare check-in features if user wish to use. This feature is very much needed because some users are reluctant use several applications doing the same function or get rid of social connectivity.
to get a highlevel idea, refer sample api on the following link https://docs.google.com/file/d/0B3v8S0e-PvVpdWFJOVhqc1d2SHc/edit?usp=sharing
Above check-in API located at ABC facade is an example for usage of Facade.
It has our service API and also facebook and foursqure check-in capabilities based on client's selection. Facebook and foursqure APIs can have specific implementations (SOAP, Restful, etc. ) and security (OAuth etc.) requirements etc.
Satisfying one of these APIs (facebook, foursqure) requirements needs to fulfil different set of tasks. these will be different sub systems with in our check in requirement.
So facade's simplistic usage is to satisfy several sub systems triggered by one simple method
But if we consider our own API which is check-in API located at MngCheckinSvc. This is a service layer API. This is the API that contains our application's check in requirements. This is the API provide public access from your MngCheckinSvc to handle check-in requirement to application.
This will have complex inner behaviors but still most of them will be application specific logic implementations.
This API(MngCheckinSvc.checkin(....)) might access different set of DAOs, Internal APIs, may be other internal services etc. in order to fulfill merchant check-in with in the application.
In my experience, most distributed object technologies (RMI, CORBA, etc.) work something like this:
define a service interface
write an implementation of the interface
use a tool (rmic, IDL compiler, etc.) that generates code which enables a client to get a reference to an implementation of the interface given some endpoint (URL).
The important point is that the service interface is a shared contract that both the client and service must adhere to. I've had a look at metro, and it doesn't seem to follow this pattern.
I'm looking for alternative suggestions that do support this kind of interface-based web service development. Unfortunately, I'm required to use SOAP, so libraries that only support RESTful services are no good to me.
Ideally, I would like to follow a code-first, rather than a contract-first appeoach, i.e. I define the (Java) service interface and the WSDL is generated from that, rather than the other way around.
Solutions that support defining or implementing the service using Groovy (instead of Java) are particularly welcome.
Metro allows you to annotate a given method, put a hint or two about the endpoints in the servlet container configuration files, and then have the WSDL generated automatically on request.
This is very nice, and save you all the trouble of having to create a full WSDL for just exposing a method or two.
Metro is good (+1), but Apache CXF's Simple Frontend goes one step further: you don't have to annotate anything. It generates WSDLs, clients and servers from plain Java interfaces.
I need to create a system oriented around Methods where providers can register for the Methods they handle and consumers can do two things (for now) - either get Metadata for a method or execute it. I'm considering creating a REST style architecture where methods are resources with unique URIs and an interface consisting of two methods - getMetadata and Execute.
I'll need to have an equivalent of #RequestMapping so that the provider that handles specific methods can be located by the central dispatcher. As a result the provider will return either Model or Metadata object.
This looks pretty similar to Spring MVC but I don't want to expose and consume my resources(methods) over the web and use http as this will incur unnecessary overhead. Instead I want to use it like a standard java API where java methods are called and java objects are transferred.
I can do that by writing my own equivalent of #RequestMapping and Dispatcher logic but I was wondering if there's a better way to do this with Spring. Any suggestions?
Thanks!
Kostadin
You are saying you want to do using REST and everything will have a unique URI but not over HTTP?? Sounds like you are looking for RMI or something similar... Chech Burlap or Hessian both of them has excellent support from spring.
There's software out there called NetKernel that might interest you. Its literature says that it is an implementation of Resource-Oriented Computing. It looks like it rigorously separates its logical computing model from the physical details. It's RESTful, defining a resource model, a limited set of verbs, and a naming scheme. Implemented in Java. Comes with HTTP and other transports built in.
It doesn't have a Java in-process transport, but you could probably write one for it pretty easily.
Hmm...if you never need to process requests from out-of-process sources, it's probably overkill for you, but maybe it will show you some useful patterns.
I've just finished reading about SOAP via Spring-WS in "Spring in Action", 2nd edition, by Craig Walls from Manning Publications Co. They write about Contract First, much like the Spring docs, with making a message and method XML and then transforming that to XSD and then again to WSDL, while wiring up the marshalling and service path in Spring.
I must admit, I'm not convinced. Why is this a better path than, let's say, making a service interface and generating my service based on that interface? That's quite close to defining my REST #Controllers in Spring3. Do I have options of going a path like this with making SOAP webservices with Spring?
Also: I'd like to duplicate an already existing webservice. I have its WSDL and I can have my service placed instead of it. Is this recommended at all? If so, what's the recommended approach?
Cheers
Nik
I think you must have your wires crossed.
Contract first means defining a WSDL, and then creating Java code to support this WSDL.
Contract last means creating your Java code, and generating a WSDL later.
The danger with contract last is if your WSDL is automatically generated from your Java code, and you refactor your Java code, this causes your WSDL to change.
Spring-WS only supports contract first
2.3.1. Fragility
As mentioned earlier, the
contract-last development style
results in your web service contract
(WSDL and your XSD) being generated
from your Java contract (usually an
interface). If you are using this
approach, you will have no guarantee
that the contract stays constant over
time. Each time you change your Java
contract and redeploy it, there might
be subsequent changes to the web
service contract.
Aditionally, not all SOAP stacks
generate the same web service contract
from a Java contract. This means
changing your current SOAP stack for a
different one (for whatever reason),
might also change your web service
contract.
When a web service contract changes,
users of the contract will have to be
instructed to obtain the new contract
and potentially change their code to
accommodate for any changes in the
contract.
In order for a contract to be useful,
it must remain constant for as long as
possible. If a contract changes, you
will have to contact all of the users
of your service, and instruct them to
get the new version of the contract.
Toolkit's point about Java interfaces being more brittle is correct, but I think there's more.
Just like there's an object-relational impedance mismatch, there's also an object-XML mismatch. The Spring web service docs do a fine job of explaining how collections and the rest can make generating an XML document from a Java or .NET class problematic.
If you take the Spring approach and start with a schema you'll be better off. It'll be more stable, and it'll allow "duck typing". Clients can ignore elements that they don't need, so you can change the schema by adding new elements without affecting them.
Currently, I only know a way of doing RPC for POJOs in Java, and is with the very complex EJB/JBoss solution.
Is there any better way of providing a similar functionality with a thiner layer (within or without a Java EE container), using RMI or something that can serialize and send full blown objects over the wire?
I'm not currently interested in HTTP/JSON serialization BTW.
EDIT: For clarification: I'm trying to replace an old EJB 2.1/JBoss 4 solution with something more easy to manage at the container level. I need to have entire control over the database(planning to use iBATIS which would allow me to use fairly complex SQL very easily), but the only things I want to keep over the wire are:
Invocation of lookup/data modification methods (automagic serialization goes here).
Transparent session control (authentication/authorization). I still have to see how to accomplish this.
Both items have to work as a whole, of course. No access should be granted to users without credentials.
Because I'm not very fond of writing webapps, I plan to build a GUI (Swing or SWT) that would only manage POJOs, do some reporting and invoke methods from the container. I want the serialization to be as easy as possible.
As is nearly always the case, Spring comes to the rescue. From the reference documentation, you will want to read Chapter 17. Remoting and web services using Spring.
There are several methods to choose from. The beauty of Spring is that all your interfaces and implementations are vanilla POJOs. The wiring into RMI or whatever is handled by Spring. You can:
Export services using RMI:
probably the simplest approach;
Use HTTP invoker: if remote access is an issue, this might be better for firewalls, etc than pure RMI; or
Use Web Services, in which case I would favour JAX-WS over JAX-RPC.
Spring has the additional benefit in that it can do the wiring for both the server and the client, easily and transparently.
Personally I would choose either (2) or (3). HTTP is network friendly. It's easy to deploy in a Web container. Jetty's long-lived connections give you the option over server push (effectively) over HTTP.
All of these methods allow complex objects to be sent across the wire but they are subtly different in this regard. You need to consider if your server and client are going to be distributed separately and whether it's an issue if you change the interface that you need to redistribute the class files. Or you can use a customized serialization solution (even XML) to avoid this. But that has issues as well.
Using a Web container will allow you to easily plug-in Spring Security, which can be a bit daunting at first just because there are so many options. Also, HttpSession can be used to provide state information between requests.
Simple RPC is exactly what RMI was built for. If you make a serializable interface, you can call methods on one app from another app.
If you only need value objects then just ensure the POJOs implement Serializable and write the objects across sockets (using ObjectOutputStream). On the receiving end read the objects using ObjectInputStream. The receiving end has to have a compatible version of the POJO (see serialVersionUID).
Hessian/Burlap 'protocol-ize this: http://hessian.caucho.com/ and http://www.caucho.com/resin-3.0/protocols/burlap.xtp
You could try XStream (http://x-stream.github.io/) over REST. Easy to apply on e pre-existing set of pojos.
Can you give some further information as to what you're trying to achieve, since you're not interested in rest/json ?