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;
}
Related
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
I have inherited a Java web service project that is using Dagger 2. Based on my so far limited understanding of Dagger I am confused as to why every single class that is injected has the singleton annotation on it in the dagger module class's. If I was creating this application without dagger they would not all be singletons, is this something specific to dagger or have the previous developers simply misused Dagger?
[...] every single class that is injected has the singleton annotation [...] is this something specific to dagger [...]?
Nope. #Singleton is the only scope included with Dagger by default, but you can also create custom scopes, use #Reusable which may create multiple objects but will reuse them if possible, or no scope at all.
or have the previous developers simply misused Dagger?
If possible you should just ask them. If every object is a Singleton this looks like they did not invest a lot of thought in the setup and just copy-pasted declarations, at least this would be my assumption.
From the section about Reusable in the user guide:
Sometimes you want to limit the number of times an #Inject-constructed
class is instantiated or a #Provides method is called, but you don’t
need to guarantee that the exact same instance is used during the
lifetime of any particular component or subcomponent. This can be
useful in environments such as Android, where allocations can be
expensive.
Two main differences:
#Singleton annotated class is guaranted to give always the same instance. It is needed if we keep global state in it. #Reusable do not give any guarantee.
If any class requests the instance of #Singleton annotated class, double checking is performed (which is slow). In case of #Reusable, it isn't.
I'd use #Reusable scope for classes that are expensive to build (for example I'm using for Retrofit instance - but to be honest I've never made performance tests if it is worth to use this annotation at all).
On the other hand, I'm using #Singleton annotated class for the cache.
Also, if you have class which keeps encapsulated global state like this:
class StateWrapper {
final State state;
#Inject
StateWrapper(State state) {
this.state = state;
}
}
I mean the state is de facto kept in the State class, do not annotate StateWrapper as #Singleton, always annotate the smallest part: in this case the State class.
(This hint is taken from the video)
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'm wondering how I can bind a singleton to a parameter in a provider.
ie:
#Singleton
public class RunButtonController{
#Inject
public RunButtonController(EventBus eventbus){ ... }
public JComponent getView(){
return view;
}
...
}
public class UncaughtExceptionController{
#Inject
public UncaughtExceptionController(
EventBus eventBus, ...,
#Named(DefaultExceptionViewKey) JComponent defaultView)
{ ... }
...
}
public class GUIController{
//another consumer of RunButtonController, arguably the "main" consumer.
#inject
public GUIController(RunButtonController runButtonController,
UncaughtExceptionController uncaughtExceptionController, ...)
{ ... }
...
}
public class Bootstrapper{
public static void main(String[] args){
Injector injector = Guice.createInjector(new OptipModule());
GUIController controller = injector.getInstance(GUIController.class);
}
private static class OptipModule extends AbstractModule{
#Override
protected void configure() {
bind(EventBus.class).toInstance(new EventBus("OPTIPGlobalEventBus"));
bind(JFrame.class).to(GUIView.class);
}
#Provides #Named(DefaultExceptionViewKey)
public JComponent getFrom(RunButtonController runButtonController){
return runButtonController.getView();
}
}
}
Putting a breakpoint on my RunButtonController constructor, I can see it consistently getting instanced twice. I want it to only be instanced once, and I want
defaultExceptionViewProvider == runButtonController
to be true.
I've used Castle Windsor fairly extensively, but that's the only IOC container I've used, so I'm new to guice. I'm seeing remnants of visitor behavior all over the place, and guice's documentation makes it pretty clear that the defined behavior of a class (ie, instance once, use this instance, use this factory, ...) doesn't persist beyond the module it was configured for. I'd like to say that I saw it written that when you use an #Provides, guice creates a child module for you, so presumably what I need to do is tell this child #Provides-generated module that 'hey, this class is a singleton and I'm in the process of resolving it, so here it is! don't use your own!'
I think that I'm going about this framework the wrong way. I've been smashing down annotations and hitting debug, but perhaps what I really need to do is spend a few hours reading a good tutorial, unfortunately I cannot find one. The JavaDoc has examples, and the webpage publishes them, but they give you very little context and so, having read the article on #Assisted three times, I still don't understand it (perhalps that's what I should be using?) Bonus points for somebody who points in the direction of a particularly detailed blogger and a guice entry on his page.
Along those lines, and digressing enormously, I'm wondering what the ramifications are of me trying to pushing this 'hey your default notification area is this other guys view' into my IOC container. Is that maybe domain logic? I don't really want the UnhandledExceptionController to know that its view was provided by a RunButtonController, and similarly I don't want the RunButtonController to know its view is being used for anything other than being stamped out onto the view tree.
thanks for reading!
As posted, it looks like your code should work. That said, there are a few caveats that could cause singletons to coexist. Double-check the stack trace for each of the constructor calls.
It may be obvious, but you can create any number of instances outside of Guice's control, and Guice has no way of knowing those instances exist. Double check that nothing in your code calls the RunButtonController constructor manually.
Singleton behavior is enforced within any given injector. If you have two or more injectors in your application, they could each create their own instance of RunButtonController. A singleton declared in a parent injector would be visible to any child injectors, though.
Singletons work by key. If you were to remove the #Singleton annotation and add this:
bind(RunButtonController.class)
.annotatedWith(Names.named("Foo"))
.asEagerSingleton()
Then injecting RunButtonController would get you a new instance every time, but injecting #Named("Foo") RunButtonController would get you a separate singleton instance that would return the same every time. That probably doesn't apply to you, because the #Singleton is on the class itself, but it has bitten others before.
You don't seem to rely on inheritance, but remember that singleton annotations don't inherit from superclass to subclass.
Side note: #Provides methods don't work via child injectors, but private modules do (alluded to as "parent injectors" in the documentation). Internally, it's true that a separate internal module is responsible for calling those provider methods, but that doesn't really matter—singletons are shared between modules.
Regarding your digression about sharing views: You're doing fairly well already by injecting #Named(DefaultExceptionViewKey) JComponent instead of RunButtonController, but if you wanted to be even more implementation-agnostic, you could create an ExceptionHandlerComponent interface and code against that.
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>