What is the definition of a Service object? - java

I've been working a lot with PHP.
But recently I was assigned some work which uses Java. In PHP I used to do a lot of Singleton object but this pattern has not the same signification in Java that it has in PHP.
So I wanted to go for an utility class (a class with static method) but my chief doesn't like this kind of classes and ask me to go for services object.
So my guess was that a service object is just a class with a constructor that implement some public methods...
Am I right?

Domain-Driven Design defines a Service as:
A SERVICE is an operation offered as an interface that stands alone in the model, without encapsulating state... [p. 105]
Yes, it's a class with public methods, but in addition to that, it implements an interface that exposes those methods. At its core, the Service is the interface - the class that implements it is just an implementation detail.

I found another definition for a service object instead that one described as an interface for concrete classes that are about to provide a certain service through that API definition set by the interface.
Article about Microservices >Link definition for service object:
3: Many object-oriented designers, including ourselves, use the term service object in the Domain-Driven Design sense for an object that carries out a significant process that isn't tied to an entity. This is a different concept to how we're using "service" in this article. Sadly the term service has both meanings and we have to live with the polyseme.
What I understand here its not the technical aspect like defining it as an "interface" but more the design concept it describes. I also understand an service object simply a domain of a class like its responsibility. So if you are developing web apps you might have a service object SecurityService which is a component of a SecurityController. The controller is calling the service to actually process security (the domain) specific services.

Related

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

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

Is there a difference between extending ServiceTracker class and implementing ServiceTrackerCustomizer interface when tracking OSGi services?

I am creating some OSGi bundles. They register services and also get (and of course use) each other's services.
I decided to use ServiceTracker instead of Declarative Services.
As I was searching for information about this I found two approach of tracking services.
The first one is creating an own tracker class for each service, which extends the ServiceTracker class and overrides the methods that need to be overridden. Then in the activator class creating a new instance of this tracker class giving the bundle context to it and open it for tracking.
The other approach is creating a tracker class for each service, which implements the ServiceTrackerCustomizer interface and overrides the methods that need to be overridden. Then in the activator class creating a new instance of the ServiceTracker class giving to it the bundle context, the name of the service that needs to be tracked and a new instance of our customizer class. Then open it for tracking.
Are there any differences between the two approaches? I would say no. In the ServiceTracker javadoc I can see that the ServiceTracker class also implements the ServiceTrackerCustomizer interface.
Could you please tell me the pros and cons on both the approaches? Thanks in advance.
Here are my reasons:
Sub-class ServiceTracker if
You want to hard-code the constructor parameters of the super class. E.g.: Hardcode the type or filter. In this case it would not look nice if all of the users should know what filter the tracker should be instantiated with
You want to override (wrap) open, close or other functions of ServiceTracker
You want to extend the functionality of ServiceTracker. E.g.: By having an implementation that pre-filters service objects based on Java Generics equality
Implement the interface if:
You expect to switch to other ServiceTracker implementation in the future. ServiceTracker is an add-on for OSGi core, it is only part of the core spec since 5.0.0. Other, more effective implementations can be created in the future
You do not want to decide which constructors you want to override as the parameters are flexible from the view point of your business logic. Probably there will be more constructors of the standard ServiceTracker class in the future. If you sub-class it, your class will not support those constructors
You want to sub-class from another class in the implementation of ServiceTrackerCustomizer
Do not use ServiceTracker directly if
Declarative Services or other Component Model helps you writing cleaner and more stable code
In over 12 years of developing with OSGi I don't think I have ever written a single ServiceTrackerCustomizer. IMHO it's just more convenient to directly subclass ServiceTracker and leave the customizer parameter null.
One simple reason it's easier to subclass is that you don't need to provide an implementation of the modifiedService method, which is rarely needed.
Functionally, however, the result will be the same so it's very much a personal preference.

Implementing an interface from a framework vs simple java interface

This concept is unclear with me.
I have worked on several frameworks for an instance Spring.
To implement a feature we always implement some interfaces provided by the framework.
For an instance if I have to create a custom scope in Spring, my class implements a org.springframework.beans.factory.config.Scope interface. Which has some predefined low level functionality which helps in defining a custom scope for a bean.
Whereas in Java I read an interface is just a declaration which classes can implement & define their own functionality. The methods of an interface have no predefined functionality.
interface Car
{
topSpeed();
acclerate();
deaccelrate();
}
The methods here don't have any functionality. They are just declared.
Can anyone explain this discrepancy in the concept? How does the framework put some predefined functionality with interface methods?
It doesn't put predefined functionality in the methods. But when you implement
some interface (say I) in your class C, the framework knows that your object (of type C)
implements the I interface, and can call certain methods (defined in I) on your object
thus sending some signals/events to your object. These events can be e.g. 'app initialized',
'app started', 'app stopped', 'app destroyed'. So usually this is what frameworks do.
I am talking about frameworks in general here, not Spring in particular.
There is no conceptual difference, actually. Each java interface method has a very clear responsibility (usually described in its javadoc). Take Collection.size() as an example. It is defined to return the number of elements in your collection. Having it return a random number is possible, but will cause no end of grief for any caller. Interface methods have defined semantics ;)
As I mentioned in the comments, to some extent, implementing interfaces provided by the framework is replaced by the use of stereotype annotations. For example, you might annotate a class as #Entity to let Spring know to manage it and weave a Transaction manager into it.
I have a suspicion that what you are seeing relates to how Spring and other frameworks make use of dynamic proxies to inject functionality.
For an example of Spring injecting functionality, if you annotate a method as #Transactional, then the framework will attempt to create a dynamic proxy, which wraps access to your method. i.e. When something calls your "save()" method, the call is actually to the proxy, which might do things like starting a transaction before passing the call to your implementation, and then closing the transaction after your method has completed.
Spring is able to do this at runtime if you have defined an interface, because it is able to create a dynamic proxy which implements the same interface as your class. So where you have:
#Autowired
MyServiceInterface myService;
That is injected with SpringDynamicProxyToMyServiceImpl instead of MyServiceImpl.
However, with Spring you may have noticed that you don't always need to use interfaces. This is because it also permits AspectJ compile-time weaving. Using AspectJ actually injects the functionality into your class at compile-time, so that you are no longer forced to use an interface and implementation. You can read more about Spring AOP here:
http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#aop-introduction-defn
I should point out that although Spring does generally enable you to avoid defining both interface and implementation for your beans, it's not such a good idea to take advantage of it. Using separate interface and implementation is very valuable for unit testing, as it enables you to do things like inject a stub which implements an interface, instead of a full-blown implementation of something which needs database access and other rich functionality.

Advice wanted on a complex structure in java (DAO and Service Layer linking/coupling)

Introduction
I am trying to make a rather complex structure in Java with interfaces, abstract classes and generics. Having no experience with generics and only average experience with creating good OOP designs, this is beginning to prove quite a challenge.
I have some feeling that what I'm trying to do cannot actually be done, but that I could come close enough to it. I'll try to explain it as brief as I can. I'm just going to tell straight away that this structure will represent my DAO and service layers to access the database. Making this question more abstract would only make it more difficult.
My DAO layer is completely fine as it is. There is a generic DAO interface and for each entity, there is a DAO interface that extends the generic one and fills in the generic types. Then there's an abstract class that is extended by each DAO implementation, which in turn implement the corresponding interface. Confusing read for most probably, so here's the diagram showing the DAO for Products as an example:
Now for the service classes, I had a similar construction in mind. Most of the methods in a service class map to the DAO methods anyway. If you replace every "DAO" in the diagram above with "Service", you get the basis for my service layer. But there is one thing that I want to do, based on the following idea I have:
Every service class for an entity will at least access one DAO object, namely the DAO of the entity that it is designed for.
Which is...
The question/problem
If I could make a proper OO design to make each service class have one instance variable for the DAO object of their respective entity my service layer would be perfect, in my view. Advice on this is welcome, in case my design is not so good as it seemed.
I have implemented it like this:
Class AbstractService
public abstract class AbstractService<EntityDAO> {
EntityDAO entityDAO;
public AbstractService() {
entityDAO = makeEntityDAO(); //compiler/IDE warning: overridable method call in constructor
}
abstract EntityDAO makeEntityDAO();
}
Class ProductServiceImpl
public class ProductServiceImpl extends AbstractService<ProductDAOImpl> {
public ProductServiceImpl() {
super();
}
#Override
ProductDAOImpl makeEntityDAO() {
return new ProductDAOImpl();
}
}
The problem with this design is a compiler warning I don't like: it has an overridable method call in the constructor (see the comment). Now it is designed to be overridable, in fact I enforce it to make sure that each service class has a reference to the corresponding DAO. Is this the best thing I can do?
I have done my absolute best to include everything you might need and only what you need for this question. All I have to say now is, comments are welcome and extensive answers even more, thanks for taking your time to read.
Additional resources on StackOverflow
Understanding Service and DAO layers
DAO and Service layers (JPA/Hibernate + Spring)
Just a little note first: usually in an application organized in layers like Presentation / Service / DAO for example, you have the following rules:
Each layer knows only the layer immediately below.
It knows it only by it's interfaces, and not by it's implementation class.
This will provide easier testing, a better code encapsulation, and a sharper definition of the different layers (through interfaces that are easily identified as public API)
That said, there is a very common way to handle that kind of situation in a way that allow the most flexibility: dependency injection. And Spring is the industry standard implementation of dependency injection (and of a lot of other things)
The idea (in short) is that your service will know that it needs a IEntityDAO, and that someone will inject in it and implementation of the interface before actually using the service. That someone is called an IOC container (Inversion of Control container). It can be Spring, and what it does is usually described by an application configuration file and will be done at application startup.
Important Note: The concept is brilliant and powerful but dead simple stupid. You can also use the Inversion of Control architectural pattern without a framework with a very simple implementation consisting in a large static method "assembling" your application parts. But in an industrial context it's better to have a framework which will allow to inject other things like database connection, web service stub clients, JMS queues, etc...
Benefits:
Your have an easy time mocking and testing, as the only thing a class depends on is interfaces
You have a single file of a small set of XML files that describe the whole structure of your application, which is really handy when your application grows.
It's a very widely adopted standard and well - known by many java developers.
Sample java code:
public abstract class AbstractService<IEntityDAO> {
private IEntityDAO entityDAO; // you don't know the concrete implementation, maybe it's a mock for testing purpose
public AbstractService() {
}
protected EntityDAO getEntityDAO() { // only subclasses need this method
}
public void setEntityDAO(IEntityDAO dao) { // IOC container will call this method
this.entityDAO = dao;
}
}
And in spring configuration file, you will have something like that:
<bean id="ProductDAO" class="com.company.dao.ProductDAO" />
[...]
<bean id="ProductService" class="com.company.service.ProductService">
<property name="entityDAO" ref="ProductDAO"/>
</bean>

Why always have single implementation interfaces in service and dao layers?

I've worked/seen a few spring-hibernate web application projects having as many interfaces as there are actual service and dao classes.
I always thought that these two as the main reasons for having these single implementation interfaces:
Spring can wire actual implementation as dependencies in a given class (loose coupling)
public class Person {
#Autowired
private Address address;
#Autowired
private AccountDetail accountDetail;
public Person(Address address, AccountDetail accountDetail)
{ // constructor
While unit testing, I can create mock classes and test a class in isolation.
Address mockedAddress = mock(Address);
AccountDetail mockedAccountDetail = mock(AccountDetail);
Person underTestPerson = new Person(mockedAddress, mockedAccountDetail);
// unit test follows
But, of late, I realized that:
Spring can wire concrete implementation classes as dependencies:
public class Person {
#Autowired
private AddressImpl address;
#Autowired
private AccountDetailImpl accountDetail;
public Person(AddressImpl address, AccountDetailImpl accountDetail) {
// constructor
Mock frameworks like EasyMock can mock concrete classes as well
AddressImpl mockedAddress = mock(AddressImpl);
AccountDetailImpl mockedAccountDetail = mock(AccountDetailImpl);
Person underTestPerson = new Person(mockedAddress, mockedAccountDetail);
// unit test follows
Also, as per this discussion, I think the summary is that within a single app, interfaces are mostly overused probably out of convention or habit. They generally make best sense in cases where we are interfacing with another application for example slf4j used by many apps around the world. Within a single app, a class is almost as much an abstraction as an interface is.
So, my question is why do we still need Interfaces and then have single implementations like *ServiceImpl and *DaoImpl classes and unnecessarily increase our code base size. Is there some issue in mocking concrete classes that I’m not aware of.
Whenever I've discussed this with my team-mates, only answer I get is that implementing service and dao classes based on interfaces is THE DESIGN everybody follows - they mention about spring best practices, OOP, DDD etc. But I still don't get a pragmatic reason behind having so many interfaces within an isolated application.
There are more advantages to interfaces - As in proxying . If your class implements an interface , JDK dynamic proxies will be used by default for AOP . If you use the implementations directly, you'll be forced to use CGLIB proxies by making proxy-target-class=true . These require byte code manipulation unlike JDK proxies .
read here for more on this .
Read another discussion at what reasons are there to use interfaces (Java EE or Spring and JPA) for more info .
It's a very controversial subject. In brief, there's none—at least for you, the developer.
In EJB2 world, the Home and Remote interfaces were a must, and were exactly for a reason #AravindA mentions: proxies. Security, remoting, pooling, etc. all could be wrapped in a proxy, and provide the services requested strictly within standard library (as in DynamicProxy).
Now that we have javaassist and cglib, Spring (Hibernate, EJB3 if you prefer) are perfectly capable of instrumenting your classes as framework developer likes. Problem is, what they do is a very annoying thing: they usually request you to add a no-parameter constructor.—Wait, I had parameters here?—Nevermind, just add the constructor.
So interfaces are here to maintain your sanity. Still, it's strange, a no-argument constructor for a class with proper constructor is not something that makes a sense to me, right? Turns out (I should've read the spec, I know) that Spring creates a functional equivalent of an interface out of your class: an instance with no (or ignored) state and all the methods overridden. So you have a "real" instance, and a "fake interface" one, and what fake interface does is, it serves all the security/transactional/remoting magic for you. Nice, but hard to understand, and looks like a bug if you haven't taken it apart.
Moreover, if you happen to implement an interface in your class, (at least some versions of) Spring suddenly decides you were going to proxy this interface only, and the application just doesn't work for no apparent reason.
Thus, so far the reason is, safety and sanity. There are reasons why it is a good practice—but from your post, I see you already read all of those. The most important reason I can see today is the WTH/minute metric, especially if we're talking about newcomers to your project.

Categories

Resources