Do we really need ServiceFacade Design Pattern while consuming a web-service? - java

I wanted to know if ServiceFacade Design Pattern is really required while consuming a web-service.
http://soapatterns.org/design_patterns/service_facade
Any insight and code snippet would be really helpful.
Thanks in advance !!

The aim of the facade is to provide a forward (or client) facing endpoint, which in turn provides only what is needed for communication and hide anything which is behind it to the outside world.
Having a facade will allow you to abstract your behaviour without exposing it. It will also allow you to make changes without potentially affecting the endpoint itself. That depends on the type of changes obviously, but if you have some requirements which require some change in the logic it might be possible that the actual input and output of the service remain untouched.
If you where to do away with the service facade, any changes to the code might require your clients to update the code from their end, and those who, for some reason do not update might end up with a broken system or else you would have to cater for multiple versions.

Service Facade design pattern is not mandatory consuming a web-service. it is required when you don't want to expose core service contract changes.
How it works
You will define a core business service contract (CoreServiceContract)
You will define implementation for that contract (CoreServiceContractImpl)
You will define one service facade which is customer facing ( ServiceFacade )
This ServiceFacade holds the reference of contract - CoreServiceContract
You will invoke methods defined in CoreServiceContract through ServiceFacade. CoreServiceContract holds implementation of CoreServiceContractImpl
Advantages:
1) The Service Facade insulates the service definition from its implementation.
2) It is the way of decoupling the Web tier from the Business tier.
3) From a transactional point of view, the business service may implement his transaction scope or be part of the current transaction.
4) The contract of the Service Facade interface is oriented to be invoked by Web tier or client software, but methods of the contract should not be invoked
within the business implementation.
Have a look at this article for working code

Related

How does an interface remove dependency from implementation?

I am reading Uncle Bob's Clean Architecture book. One of the main points throughout the book is that you should depend on abstractions, not on implementations.
For example, he mentions that the higher layers of the software shouldn't know anything from the lower layers (which I agree). He also points out that when a higher layer needs to communicate with a lower layer, the lower layer must implement an interface that the higher layer uses. For example, if the Use Case layer needs to call the Presenter layer, it should be done through an interface OutputBoundary that is implemented by the Presenter, so the Use Case layer does not depend on the presenter. If you do it without an interface, it is really bad because the Use Case layer is depending on the Presenter layer.
How is that true? If in the future the Presenter layer needs more or different data to be sent by the Use Cases, you not only will have to modify the Presenter, but the OutputBoundary Interface and the Use Cases as well. So no, the Use Cases are never completely independent from the Presenter.
If the Presenter changes the way he presents data just changing the body of the method, then the Use Case layer won't have to change anything. If the Presenter changes the way he presents data by changing the method declaration it won't matter if you have an interface or not, because you will have to modify the method call in the Use Case layer. In none of the two cases the use of an interface really matter.
Is there something that I am missing here? I know the uses of an interface, and I know that if you have or plan to have multiple presenters, then having them to implement a common interface would be the right way to go, but even so I can't see the independence from lower layers that he mentions on his books.
How is that true? If in the future the Presenter layer needs more or
different data to be sent by the Use Cases, you not only will have to
modify the Presenter, but the OutputBoundary Interface and the Use
Cases as well. So no, the Use Cases are never completely independent
from the Presenter.
If the presenter layer needs more or different data then the use cases layer must change to provide that data.
But, if you decide to make changes in the presentation layer, or replace it for a new technology, but the information is the same, you would not need to modify the Use cases layer.
Same idea with data access, you use interfaces so it depends on application instead of the other way around, and when you need to change the data access to use a different database technology, as long as your data access layer keeps implementing the same interfaces, you don't need to make changes in application.
Imagine that Radio is higher level of software, then Battery will be lower level of dependency. In real life, Radio does not have tight coupling to Duracell battery, you can use any battery you want.
Let me show an example in C# (sorry, I do not have installed Java editor, but code is really simple):
class Radio
{
private IBattery _battery;
public Radio(IBattery battery)
{
_battery = battery;
}
public void TurnOn()
{
_battery.GiveEnergy();
}
}
interface IBattery
{
void GiveEnergy();
}
class Duracell : IBattery
{
public void GiveEnergy()
{
}
}
and usage:
IBattery battery = new Duracell();
var radio = new Radio(battery);
radio.TurnOn();
Your higher level - Radio does not depend on implementation of lower level Battery.
So you can use any battery you want.
How is that true? If in the future the Presenter layer needs more or different data to be sent by the Use Cases, you not only will have to modify the Presenter, but the OutputBoundary Interface and the Use Cases as well. So no, the Use Cases are never completely independent from the Presenter.
The answer is yes and no
Yes it is true since all layers pointing inwards not outwards
which make the communication between layers based on interfaces/abstraction the application layer as example will implement all the code against the interface and not aware with the implementation of that interface but since the higher layer pointing inward so it will consume the interface of the lower layer then implement it which makes the answer yes
every layer by itself it depend on the one lower so Application depend on Core/Entities
and Infrastructure depend on application but here is the trick in your presentation layer you actually will use DI to point the implementation of every interface to that interface which will make them depend on each others only in the run time
in this image you could see the direction of each layer
If the Presenter changes the way he presents data just changing the body of the method , then the Use Case layer won't have to change anything.
yes since the data still the same coming from application layer but if the presentation layer required completely diff let's say View model then the application layer will have to change the data which might need a change in persistence / infrastructure layer which will lead to change in the interface in application layer which persistence / infrastructure will need to implement !!!
I Actually recommend you to watch this video for Jason Taylor
https://www.youtube.com/watch?v=dK4Yb6-LxAk
Let me know if you have any questions

How to define REST service contract for shared use between several similar services?

I'm implementing a series of REST micro services in Java - let's call them "adapters".
Every service reads the data from a particular source type, and provides result in the same way. The main idea is to have the same interface (service contract) for all of them, to get interchangeability. I would like to avoid code duplication and reuse the service contract for the services.
And it seems that I'm reinventing the wheel. Is there a standard approach for this?
I tried to extract the service contract in form of Java interface for Spring MVC Controller class and accompanying DAO class CustomObject:
public interface AdapterController {
#RequestMapping(method = RequestMethod.GET, value = "/objects/{name}")
CustomObject getObject(#PathVariable final String name);
}
Then put them into separate Maven project, set it as a dependency in the original project, and rewrote REST controller class as following:
#RestController
public class DdAdapterController implements AdapterController {
#Override
public CustomObject getObject(String name) {
return model.getByName(name);
}
I can reuse DAO object in a client code as well, but the interface class is useless at client side.
1) Summarizing: is it OK to reuse/share service contract between different service implementations? What's the cost of this? Is there the best practice how to share service contract?
2) The next question is about service contract and consuming client. Is it OK to share the contract between service and client? Is there some tools in Java / approach for this?
This goes against the microservice mentality and in the long run is a bad idea to share code.
If you start sharing code you will slowly just build a distributed monolith, where multiple services are dependent on each other.
Many have talked about this earlier:
microservices-dont-create-shared-libraries
The evils of too much coupling between services are far worse than the problems caused by code duplication
Micro services: shared library vs code duplication
The key to build microservices is:
One service should be very good at one thing
Keep them small
Have an extremely well documented api
When you need to delete a microservice this should be done with as few needs to update other services
Avoid code sharing, and treat all libraries like 3rd party libraries even your own
Microservises should by loosely coupled = minimum dependencies.
Microservices is an
architectural style that structures an application as a collection of
services that are
Highly maintainable and testable
Loosely coupled
Independently deployable
Organized around business capabilities.
https://microservices.io/
Contract can be defined with WADL
Using contract between client and server means less bugs, less missunderstandings when implementing client. That is what the contract good for.

Business Delegate Vs Service Locator

What is the difference between Business Delegate and Service Locator.Do both responsible for encapsulating lookup and creation mechanism.If Business Delegate uses Service Locator for hiding lookup and creation mechanism then what is Business Delegate exclusively meant for, can't Service Locator replace Business Delegate.
I don't know if you already checked this out, but it's a good start.
Use a Business Delegate to encapsulate access to a business service. The Business Delegate hides the implementation details of the business service, such as lookup and access mechanisms.
A Service Locator encapsulates the logic required to search and/or obtain the location, restrictions and required fields for a certain service based on a general registry. A Business Delegate encapsulates a group of related services and exposes them in a cohesive way to prevent a service customer from having to search and access all the services related to a certain functionality.
Plus, you prevent the customer from having to actually know the Service Locator and the services it should consume, leaving that to a particular Business Delegate. A client only needs that delegate to perform a group of related tasks or a task that relies in various services.
Example
A Business Delegate doesn't actually encapsulate a group of Service Locators. It provides an abstraction layer over a Service Locator to provide a cohesive subset of services. Usually there's only one instance of a Service Locator, multiple instances require an additional mapping where you should know WHICH Service Locator provides Service X, think of it as if you would need a Service Locator Locator.
An example should help clarify things.
Think about user account management. The UserBusinessDelegate looksup the registration service to register an user and then looksup the authentication service to allow a log in. The client only needs one Business Delegate to access those services and he doesn't need to know the id of both services.
Those service ids are encapsulated in the UserBusinessDelegate avoiding the need of declaring the ids and using a Service Locator everywhere. Think about this, what would happen if one service id changes?.
In such cases the Business Delegate in charge is updated, avoiding a direct impact for the client.
These patterns have a common point therefore this question have a lot of sense.
Both of them help a client to consume a service.
Let suppose that we have services exposed as EJB, WS or POJO.
The client may access such services using the Service Locator directly. (allowing some complexity to be encapsulated inside this component)
This improve the cliente's side code but the client is still responsible for knowing how the service is exposed. (He has to select the right Service Locator for the specific service).
One disadvantage of this solution is that the client would be highly coupled with the service.
For example:
a) if tomorrow the service that is exposed as an EJB changes to WS we have to change the client's code (use another Service Locator).
b) If we want to test the client's code using a mock service, we have to change code.
Business Delegate come to scene to decrease the level of coupling.
Now the client interacts (in a higher abstraction level) with the Business Delegate, therefore he doesn't need to know anything else about service implementation details.
Of course the Service Locator is still useful due to the Business Delegate interacts with him.
At the simplest way, I like to think aboutn Business Delegate as an interface (improves decoupling) and a Service Locator as a helper (encapsulates infrastructure related behavior)

On properly implementing complex service layers

I have the following situation:
Three concrete service classes implement a service interface: one is for persistence, the other deals with notifications, the third deals with adding points to specific actions (gamification). The interface has roughly the following structure:
public interface IPhotoService {
void upload();
Photo get(Long id);
void like(Long id);
//etc...
}
I did not want to mix the three types of logic into one service (or even worse, in the controller class) because I want to be able to change them (or shut them) without any problems. The problem comes when I have to inject a concrete service into the controller to use. Usually, I create a fourth class, named roughly ApplicationNamePhotoService, which implements the same interface, and works as a wrapper (mediator) between the other three services, which gets input from the controller, and calls each service correspondingly. It is a working approach, though one, which creates a lot of boilerplate code.
Is this the right approach? Currently, I am not aware of a better one, although I will highly appreciate to know if it is possible to declare the execution sequence declaratively (in the context) and to inject the controller with and on-the fly generated wrapper instance.
Also, it would be nice to cache some stuff between the three services. For example, all are using DAOs, i.e. making sometimes the same calls to the DB over and over again. If all the logic were into one place that could have been avoided, but now... I know that it is possible to enable some request or session based caching. Can you suggest me some example code? BTW, I am using Hibernate for the persistence part. Is there already some caching provided (probably, if they reside in the same transaction or something - with that one I am totally lost)
The service layer should consist of classes with methods that are units of work with actions that belong in the same transaction. It sounds like you are mixing service classes when they could be in the same class and method. You can inject service classes into one another when required too, rather than create another "mediator".
It is perfectly acceptable to "mix the three types of logic", in fact it is preferable if they form an expected use case/unit of work
Cache-ing I would look to use eh cache which is, I believe, well integrated with hibernate.

How to learn "separation of concern" in java

In another question, someone told me to implement the following in my java program. But, I am very new to Java and I do not know how to start to convert my simple program into this structure:
Data Access Layer (read/write data)
Service Layer (isolated business logic)
Controller (Link between view and model)
Presentation (UI)
dependency injection.
program to the interface:
Does that come inside some framework? Should I start learning Spring and this structure will evolve naturally? Or, can I implement above technologies one by one without using a framework?
You can implement them without a framework if you wish, but you give up whatever benefits the framework offers you.
The layering you cite is correct and independent of any framework; it's just programming to interfaces and separation of concerns. You're free to do it without Spring if you wish to minimize the number of new technologies you want to learn right now.
If you don't know what persistence is, then you shouldn't jump into Spring. Persistence means storing data in relational databases using SQL to most people. If you don't know that, I'd recommend starting there.
All the patterns books in the world won't help you if you've never used the underlying technologies.
If you've never done any of this, I'd recommend sticking to straight JDBC, servlets, and JSPs using only JSTL (no scriptlets). Anything beyond that will just be confusing.
If you had a Foo model object, with persistence, service, and view tiers, the interfaces might look like this:
package model;
/**
* A model object that's interesting from your problem's point of view
*/
public class Foo
{
}
package persistence;
/**
* CRUD operations for a Foo
*/
public interface FooDao
{
Foo find(Long id);
List<Foo> find();
void saveOrUpdate(Foo foo);
void delete(Foo foo);
}
package service;
/**
* Just a data service that wraps FooDao for now, but other use cases would
* mean other methods. The service would also own the data connection and manage
* transactions.
*/
public interface FooService
{
Foo find(Long id);
List<Foo> find();
void saveOrUpdate(Foo foo);
void delete(Foo foo);
}
package view;
/**
* A class that owns services, validates and binds input from UI, and handles routing
* to the next view once service is complete.
*/
public interface FooController
{
ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response);
}
These are just interfaces, of course. You'll need to provide implementations.
You might want to check out Domain Driven Design. The Code samples are in Java. The things you listed are design related more than any specific technology.
In short:
Data Access Layer is a module of your application that provides interface to your data. Data may be in SQL database, XML, file wherever. You write interfaces and classes that provide interface to access data usually as VO or DTO via DAOs
Service Layer contains most of the use-case logic. Service layer interacts with Data Access Layer to perform tasks in given use case. I did not find a good article on introductory service layer. You may see here and there
Controller is the one that interacts with Service Layer and/or Data Access Layer and/or other controllers in order to perform a specified client's tasks. For example, a sign-off button controller will request a sign-off action/service to invalidate user's sessions on all services that user is logged on to, then it will choose an appropriate view or log-off web-page to forward user to.
Presentation is your user interface. It can be a web-page made of HTML or Java Swing window or anything that user interacts with. GUI commonly known term for it. This is what your users will be interacting with using mouse clicks, scrolls, swipes, drag-and-drop. These actions are mapped with controller which performs action based on what user performed on UI.
Dependency Injection is a way to wire various components. There are a lot of resources on web. You can look in Martin Fowler's this article. It's basically a mechanism that allows components to behave much like plug-and-play devices, if you know what plug goes where.Spring is a good implementation of dependency injection. You may not want to write your own framework, and at this stage, you should rather not. There is a Spring MVC framework that can do things for you.
But I suggest you start from very basic. Instead of jumping on jargon, read from basic. Start with a good book on application development using Java. You can also look into
Design Patterns - Gang of Four
Core J2EE Patterns
Developing a Spring Framework MVC application step-by-step
dependency Injection with the Spring Framework
You can implement all of this is you want -- it's been done many times before, but nothing prevents you from doing it again.
What would be a better use of your time is to make sure you understand the separation of concerns you listed above (which are generally right) and identify the most efficient integration of existing frameworks to leverage (e.g., Hiberante, Spring, Guice, etc). There are multiple answers for that one (and no shortage of opinions!), but all things being equal, the less frameworks you have to integrate, the easier and better fitting it's likely to be.
Spring has a very well known framework which covers many of these things, so it would be wise to start there. It also allows you to work with other frameworks (i.e., you can use selective parts of Spring). For example, you can use Spring for dependency injection and use a different MVC framework.
It is very hard to answer this question. First of all, I don't know what your program looks like. Second, I don't think 'converting' it is something that can be done, or should be done for that matter. What you're talking about are architectural concepts that the developers usually have in mind while designign the application.
If these concepts interest you, I suggest reading a bit about Model-View-Controller pattern (MVC) and service-oriented Architecture (SOA).
These are general concepts that do not apply specifically to Java. However, they are widely used in Java enterprise development. Various frameworks allow you to create applications utilizing these concepts. For example, Spring Web MVC, as others have pointed out, is part of the Spring Framework that lets you create web applications that adhere to the MVC pattern.
If your program is really simple this separation might be done by using one calss for each
category.
Data Access Layer (read/write data) -> one class for presisting laoding
Service Layer (isolated business logic) -> one calss with bussiness logic
Controller (Link between view and model) -> in simple swing app this merges with UI
Presentation (UI) -> one class for one widnow
dependency injection -> not used in small apps
program to the interface -> Your service class should use interface tah is used by other class instead of directly your serivce implementation:
if it's not as simple program you might want to have package for each category.
BUT - don't overdesign! These concepts are ment to help you manage large scale applications, not to ruin you in your programming begginigs!

Categories

Resources