I have got a mapper class which does a complex mapping of one pojo to another. I made the mapper class a bean and wired it to the service class. I could have made the mapper class a static class as well but I preferred a bean because I felt it better in a testability point of view, I can test the service and mappers independently by mocking the mappers. Indeed it’s also possible to mock the static classes but I will have to use powermock or something similar. Another reason to choose a bean is that for certain mappers I had to use interfaces so that I can choose the mapper implementation based on certain data conditions.
This implementation as a bean has triggered a controversy in my team with suggestions to implement it as a class with static map method or to create new mapper objects every time. And we are trying to figure out what is the best solution. Are there any industry standards being followed. Are there any trade offs with the beans approach? Can it have any impact on the performance of my application? imagine that I have got a hundred such mappers. Below is a simple Skelton of how my service and mappers looks like.
#Service
class CustomerService { #Autowired CustomerMapper customerMapper ...}
#Component
class CustomerMapper { #Autowired CustomerContactMapper ..
}
interface CustomerContactMapper {}
#Component
class InternalCustomerContactMapper implements CustomerContactMapper {}
#Component
class ExternalCuatomerContactMapper implements CustomerContactMapper {}
Well, there can be many opinions, if you want to follow conventions suggested by spring, then you did everything right.
Basically your point of testability is valid although its better to use constructor injection in this case because in the unit test you see exactly what is the required dependency:
class CustomerService {
private final CustomerMapper customerMapper;
public CustomerService(CustomerMapper customerMapper) {
this.customerMapper = customerMapper;
}
}
Side note: if you don't like the "boilerplate" of constructor, you can use Lombok that provides "AllArgsConstructor" anyway.
Now some points regarding the performance:
Spring initializes beans during the startup of the application. If these are simple-to-create classes (classes that do not load a lot of stuff upon creation, don't go to the db and so forth, just plain java objects) than it takes particles of second to initialize them all.
Later you have a regular function call (ok, if you work with interface then its a "virtual" call), but in general it doesn't affect the performance, in other words if the app works slow, the reason is likely to be anywhere else.
Regarding the alternative:
I didn't totally understand what does it mean "implement as a static class", however if you want to create a new mapper every time, this would mean that its not thread safe. In the current implementation the service is a singleton, so there won't be many instances of it, it will be only one instance per application context. However it can be called by many threads simultaneously.
So if you have to create many instances -> the mapper can't be used from many threads. This decision has nothing to do with Spring, its your code and your decision to make it non-thread safe (I'm not saying whether its good or bad, just stating the fact).
Now, if this is the case, then your solution is technically wrong. Spring supports this kind of usage via Provider class + there are other ways to inject prototype into singleton:
class CustomerService {
private final Provider<CustomerMapper> customerMapper;
You can read Here about this method
Related
We are doing some refactoring and we have hit the wall here.
There are two service classes AService and BService doing different works have a circular dependency.
Earlier they were in a different libraries so there was no circular dependency existed. But now after refactoring we have moved them into a single library into a single package.
AService job is to persist some data into a NoSQL database for a separate use case.
BService job is completely different than AService job.
AService needs BService to GET some data.
BService needs AService to write some data to NoSQL Database and reads back.
How to fix the circular dependency issue with making each of them depends on each other. Any design pattern for such issues?
class AService {
#Autowired
private BService bService;
}
class BService {
#Autowired
private AService aService;
}
The real question is why your conception making A and B dependent of each over?
It could be that A and B represent the same concept, and may be merged.
It could also be that a part of your service A or B should be extracted in a new service C.
In that last case you need to know which method depends on which service, and which one could be extracted in a new service. Without having the context and the list of methods it's difficult to propose a solution.
In the case of indirect recursive methods, you may have to cut also some methods.
Side note: don't try to find a workaround to make it work with circular dependencies, it shows a conception problem, you have to do the refactoring.
Solution 1 (recommended):
the redesign of class responsibilities. Adhering to the Single Responsibility Principle and according to the class details you revealed, we can fix your class design by extracting at least one new class: the DatabaseConnector. This class encapsulates all database related operations (CRUD) and therefore lifts the circular dependency of the service classes (without changing the original conceptions of the classes).
// This is just a raw template to express the intention
class DatabaseConnector {
void createInDatabase(Object data) {
}
Object readFromDatabase(Object args) {
}
void updateInDatabase(Object data) {
}
void deleteFromDatabase(Object data) {
}
}
class AService {
#Autowired
private DatabaseConnector dbConnector;
}
class BService {
#Autowired
private DatabaseConnector dbConnector;
}
You can add more specialized methods to the DatabaseConnector to meet special requirements (e.g. readName(), readId(), etc).
Since it is likely that more classes will need to access the database in future, you already solved or prevented new circular dependencies today. Encapsulation solved potentially upcoming problems.
Solution 2: dependency inversion
interface IAService {
}
interface BService {
}
class AService implements IAService {
#Autowired
private IBService bService;
}
class BService implements IBService {
#Autowired
private IAService aService;
}
A circular dependency is always an indicator for bad class design. In most cases the origin is the violation of the Single Responsibility Principle (the S in SOLID). A wrong composition concept can also lead to this design error. What will always help, but not fix the conceptional flaws of class responsibilities, is the introduction of interfaces to invert all dependencies (the D in SOLID). Taking the SOLID Principles serious can safe a lot of time and work and will always lead to better code (although you introduced higher code complexity).
The Mediator Pattern can also help to lift circular dependencies by encapsulating the bidirectional interaction of two or more objects.
The downside of your current code is (besides the circular dependency), that whenever class A changes and also data persistence changes, you have to touch and modify class B. This changes can break class B which is using the same persistence operations. This is true for all cases where one class has shared responsibilities with another class. If there wasn't the shared code, both classes wouldn't know each other at all. In your special case, where the dependency is cyclic, you add this flaw to the other dependency direction as well: whenever B needs to adjust or extend how to read data then you have to modify class A, which might break A. If you are using unit tests, then you would have to refactor the tests of both classes too. This tight (and cyclic) coupling of A and B will lead to errors or bugs. Extending code has become dangerous. But the good news is that circular dependencies never compile (since the dependency resolution leads to infinite recursion).
The easiest way is to move the method that Service B uses out of Service A and into Service B OR into a completely different class.
The design indicates that you probably have too many methods in Service A which Service A does not actually use, but which are public methods that should really be static and in another Class entirely.
Try to put the autowired on setter instead:
#Autowired
public void setServiceB(ServiceB service){
this.serviceB = service;
}
Service1 injects Repository1. Service2 injects Repository2.
Suppose two different scenarios:
1)
Some method of Service2 needs to retrieve data from Repository1.
Should Service2 inject Service1 or Repository1 when both of them provide respective get() method?
2) Some method of Service1 at it's end should call another method from Service2. Is it a bad practice to inject Service2 to Service1 for such needs? Is it a good practice to use event listen techniques like AOP for such needs?
There are many factors to consider here when we talked about best practices.
As a good start, try to understand the concept of SOLID principles.
Generally, it is good to have multiple classes with very focused roles that calls the other rather than combining all functionalities in one class. High reusability and least code duplication which in turn gives maintainability.
For scenario 1.)
It is perfectly fine to have a service calling another service if that business code defined in the method is the same business functionality needed by the other service. This follows the DRY principle, no redundant codes.
But it is also perfectly fine to just directly call the Dao from a service instead of calling a different service to do that for you if it is just a simple call with no further business logic. Especially if the two services are in the same module anyway, there is no strong reason to make another service a bridge class for an obvious simple single line of code unless you want to abstract it, but in your case, its just a simple get call.
For scenario 2.)
But another thing to consider is modularity and direction of dependency. If each service calls each other, there could be problem in your design, as much as possible avoid circular dependency on different modules because this could lead to spaghetti code, better to extract same code to a different class declared on common module that can be shared by many modules.
Final note, as what Robert Martin says, you won't be able to code at once the cleanest code in one round. Best codes are forged by continuous refactoring and code cleanup. To quote Robert Martin,
The Boy Scouts have a rule: "Always leave the campground cleaner than you found it."
I am not greatly experienced with this problem, but personally I would avoid coupling controllers. My first approach would be trying to create an interface that would fit all models if possible. It would then be possible to create a model that wires multiple models together to access the data you need without adding references to the controller. For instance:
Model1 implements iModel{}
Model2 implements iModel{}
ModelWrapper implements iModel{
private iModel model1;
private iModel model2;
public ModelWrapper(iModel model1, iModel model2)
{
this.model1 = model1;
this.model2 = model2;
}
public SomeDataType getSomeValue(){
SomeObject.param1 = model1.method();
SomeObject.param2 = model2.method();
return SomeObject;
}
}
I am sure there is a better way to approach the number of models passed into the constructor and also a way to search each model for the data you are looking for. If the data is not found a null reference or better a custom error could be thrown. If the implementation is consistent perhaps the wrapper could combine all models and allow access to many custom combinations. At least this way, when requirements change you can simply add an additional wrapper to get what you need without changing the current implementation.
Perhaps a more experienced developer will build on my response to provide you a better implementation, but I hope this helps.
I know it is not a best design but just a thought from a Spring newbie.
Now we can easily autowire any service method to each other conveniently in Spring framework. But What is the disadvantage to create a static factory method of the service class and call it everywhere?
It's pretty common like this:
#Autowired
CustomerService customerService;
....
AccountDetail ad = customerService.getAccountDetail(accountId, type);
But this should work too:
AccountDetail ad = CustomerService.getAccountDetail(accountId, type); //if we make getAccountDetail(String, String) static
So why there is a design like autowire? It looks fancy and really cool, but the work behind this is still create one service bean instance on another service object.
Seriously while Spring is all over the market so many posts and articles are talking about pros & renovations. But is it guaranteeing better performance(like using autowire instead of static)?
There are numerous reasons:
you can't replace CustomerService with a mock easily during tests (tools like PowerMock aside)
static methods do not participate in standard, proxy-based AOP (no transactions, security, custom aspects)
you can no longer use fancy injection techniques, like injecting HTTP request (request scoped) into singleton scoped services (poor design anyway, but...)
But to be complete, there are also advantages:
static method is actually closer to your intent, Spring beans are very rarely stateful, thus they don't really need an instance to work
static call might be faster (this is irrelevant in 99% of the programs)
What if you need to have multiple CustomerService components with different configuration? You can't do that with a single static method.
Also, if there's any configuration whatsoever on CustomerService, how do you inject it? Having a bean that gets wired into dependent objects centralizes your configuration and keeps you from having to hunt through your code.
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>
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.