Removing circular dependencies in asynchronous java application? - java

I have read up on dependency injection and interfaces, but I am still confused about the best way to decouple packages in my situation. Say I have a UIClass in UIPackage:
package UIPackage;
import NetworkPackage.NetworkClass
class UIClass() {
public static void displayMessage(String message) {
// show the message on screen
}
private static void messageEntered(String message) {
NetworkClass.sendMessage(message);
}
}
and a NetworkClass in NetworkPackage:
package NetworkPackage;
import UIPackage.UIClass;
class NetworkClass() {
public static void sendMessage(String message) {
// send the message to the network
}
private static void messageReceived(String message) {
UIClass.displayMessage(message)
}
}
These packages depend on each other, but I would like to have the network package work independently of the UI package to remove the dependency cycle. The only way I have found to do that so far is to create an interface for the UIClass to implement (UIInterface), and then an instance of UIInterface is passed to the NetworkController in the constructor or something. This seems like it just makes things more complicated though as that interface would need to be in its own package which is then included in both of the original packages.
Should I create a third package for interfaces of this type? Should I just leave the circular dependency and not worry about it?
Clarification 1
This is not the code I am actually using, I just named the packages that way so that the example would be clearer. The app uses multiple threads, which is why NetworkClass needs a references to UIClass, because it is constantly waiting for a new message while the UI may be doing other things on a different thread. When a message is received, it needs to be able to update the UI and display the message. These packages have many other classes that do other things, but for the sake of example these classes are all that is exposed.

Of course you should care, just as you should pay attention to Java coding conventions.
I think embedding "Package" in package names and "Class" in class names is brain dead. Hungarian notation fell out of favor decades ago. Take those out.
This is a bad design.
I don't know what your Network class is for. I see no reason for Network to know or care about the Client that calls it. If the Client has a reference to a Network injected into its constructor, it should be able to use it to send the call, get the response back, and display it. No good reason for giving a Client reference to Network.
No more circular dependency.
I'd expect something more like a four tier architecture:
client -> controller -> services -> persistence
This is a request/response arrangement typical of web applications. The UI sends a request to a controller/listener, which orchestrates services and persistence to fulfill the use case and send the response back to the UI.
The picture changes if you go with an asynchronous, event based architecture.

A circular dependency means generally a strong coupling between two components/things.
Is it ever a problem ?
It is very often but not always.
3 examples where it may cause an issue :
1) if the dependencies try to create themselves by passing the other as parameter. Which is obviously not possible. Using an approach that sets one of the dependency or both after instances construction is a way to solve it.
2) if the code of the dependencies changes frequently enough as a change on one class could have side effect or break the code of the other.
It is like if these classes were a single class while this is not the case.
3) if you want reuse one of the dependencies alone in other contexts or applications.
You could not as both cannot live without the other one.
So it can defeat reduce or prevent dependency reusability.

Related

How to properly use Android Room in background tasks (unrelated to UI)

At the moment Room is working well with a DB to UI integration:
Dao for DB operations
Repository for interacting with the Daos and caching data into memory
ViewModel to abstract the Repository and link to UI lifecycle
However, another scenario comes up which I am having a hard time understanding how to properly implement Room usage.
I have a network API that is purely static and constructed as a reflection of the servers' REST architecture.
There is a parser method that walks through the URL structure and translates it to the existing API via reflection and invokes any final method that he finds.
In this API each REST operation is represented by a method under the equivalent REST naming structure class, i.e.:
/contacts in REST equates to Class Contacts.java in API
POST, GET, DELETE in rest equates to methods in the respective class
example:
public class Contacts {
public static void POST() {
// operations are conducted here
}
}
Here is my difficulty; how should I integrate ROOM inside that POST method correctly/properly?
At the moment I have a makeshift solution which is to instantiate the repository I need to insert data into and consume it, but this is a one-off situation everytime the method is invoked since there is absolutely no lifecycle here nor is there a way to have one granular enough to be worthwhile having in place (I don't know how long I will need a repository inside the API to justify having it cached for X amount of time).
Example of what I currently have working:
public class Contacts {
public static void POST(Context context, List<Object> list) {
new ContactRepository(context).addContacts(list);
}
}
Alternatively using it as a singleton:
public class Contacts {
public static void POST(Context context, List<Object> list) {
ContactRepository.getInstance(context).addContacts(list);
}
}
Everything works well with View related Room interaction given the lifecycle existence, but in this case I have no idea how to do this properly; these aren't just situations where a view might call a network request - then I'd just use networkboundrequest or similar - this can also be server sent data without the app ever requesting it, such as updates for app related data like a user starting a conversation with you - the app has no way of knowing that so it comes from the server first.
How can this be properly implemented? I have not found any guide for this scenario and I am afraid I might be doing this incorrectly.
EDIT: This project is not Kotlin as per the tags used and the examples provided, as such please provide any solutions that do not depend on migrating to Kotlin to use its coroutines or similar Kotlin features.
Seems like using a Singleton pattern, like I was already using, is the way to go. There appears to be no documentation made available for a simple scenario such as this one. So this is basically a guessing game. Whether it is a bad practice or has any memory leak risks I have no idea because, again, there is just no documentation for this.

How to prevent client from seeing internal private classes in Android library ?

I have a library with several packages-
lets say
package a;
package b;
inside package a I have public a_class
inside package b I have public b_class
a_class uses b_class.
I need to generate a library from this , but I do not want the Client to see b_class.
The only solution I know of is to flatten my beautifully understandable packages to single package and to use default package access for b_class.
Is there another way to do so ? maybe using interfaces or some form of design pattern ??
If you reject to move the code to an individual, controlled server, all you can do is to hinder the client programmer when trying to use your APIs. Let's begin applying good practices to your design:
Let your packages organized as they are now.
For every class you want to "hide":
Make it non-public.
Extract its public API to a new, public interface:
public interface MyInterface {...}
Create a public factory class to get an object of that interface type.
public class MyFactory
{
public MyInterface createObject();
}
So far, you have now your packages loosely coupled, and the implementation classes are now private (as good practices preach, and you already said). Still, they are yet available through the interfaces and factories.
So, how can you avoid that "stranger" clients execute your private APIs? What comes next is a creative, a little complicated, yet valid solution, based on hindering the client programmers:
Modify your factory classes: Add to every factory method a new parameter:
public class MyFactory
{
public MyInterface createObject(Macguffin parameter);
}
So, what is Macguffin? It is a new interface you must define in your application, with at least one method:
public interface Macguffin
{
public String dummyMethod();
}
But do not provide any usable implementation of this interface. In every place of your code you need to provide a Macguffin object, create it through an anonymous class:
MyFactory.getObject(new Macguffin(){
public String dummyMethod(){
return "x";
}
});
Or, even more advanced, through a dynamic proxy object, so no ".class" file of this implementation would be found even if the client programmer dares to decompile the code.
What do you get from this? Basically is to dissuade the programmer from using a factory which requires an unknown, undocumented, ununderstandable object. The factory classes should just care not to receive a null object, and to invoke the dummy method and check the return value it is not null either (or, if you want a higher security level, add an undocumented secret-key-rule).
So this solution relies upon a subtle obfuscation of your API, to discourage the client programmer to use it directly. The more obscure the names of the Macguffin interface and its methods, the better.
I need to generate a library from this , but I do not want the Client to see b_class. The only solution I know of is to flatten my beautifully understandable packages to single package and to use default package access for b_class. Is there another way to do so ?
Yes, make b_class package-private (default access) and instantiate it via reflection for use in a_class.
Since you know the full class name, reflectively load the class:
Class<?> clz = Class.forName("b.b_class")
Find the constructor you want to invoke:
Constructor<?> con = clz.getDeclaredConstructor();
Allow yourself to invoke the constructor by making it accessible:
con.setAccessible(true);
Invoke the constructor to obtain your b_class instance:
Object o = con.newInstance();
Hurrah, now you have an instance of b_class. However, you can't call b_class's methods on an instance of Object, so you have two options:
Use reflection to invoke b_class's methods (not much fun, but easy enough and may be ok if you only have a few methods with few parameters).
Have b_class implement an interface that you don't mind the client seeing and cast your instance of b_class to that interface (reading between the lines I suspect you may already have such an interface?).
You'll definitely want to go with option 2 to minimise your pain unless it gets you back to square one again (polluting the namespace with types you don't want to expose the client to).
For full disclosure, two notes:
1) There is a (small) overhead to using reflection vs direct instantiation and invocation. If you cast to an interface you'll only pay the cost of reflection on the instantiation. In any case it likely isn't a problem unless you make hundreds of thousands of invocations in a tight loop.
2) There is nothing to stop a determined client from finding out the class name and doing the same thing, but if I understand your motivation correctly you just want expose a clean API, so this isn't really a worry.
When using Kotlin, you can use the internal modifier for your library classes.
If I understand correctly you are asking about publishing your library for 3rd party usage without disclosing part of your source? If that's the case you can use proguard, which can obfuscate your library. By default everything will be excluded/obfuscated, unless you specify things you want to exclude from being obfuscated/excluded.
If you want to distribute [part of] your code without the client being able to access it at all, that means that the client won't be able to execute it either. :-O
Thus, you just have one option: Put the sensible part of your code into a public server and distribute a proxy to access it, so that your code would be kept and executed into your server and the client would still be able to execute it through the proxy but without accessing it directly.
You might use a servlet, a webservice, a RMI object, or a simple TCP server, depending on the complexity level of your code.
This is the safest approach I can think of, but it also deserves a price to pay: In addition to complexing your system, it would introduce a network delay for each remote operation, which might be big deal depending on the performance requirements. Also, you should securize the server itself, to avoid hacker intrussions. This could be a good solution if you already have a server that you could take advantage of.

Using Proxy pattern to write a server a good idea?

For a school project, I need to write a simple Server in Java that continuously listens on an incoming directory and moves files from this directory to some place else. The server needs to log info and error messages, so I thought I could use the Proxy pattern for this. Thus, I created the following ServerInterface:
public interface ServerInterface extends Runnable {
public void initialize(String repPath, ExecutorInterface executor, File propertiesFile) throws ServerInitException;
public void run();
public void terminate();
public void updateHTML();
public File[] scanIncomingDir();
public List<DatasetAttributes> moveIncomingFilesIfComplete(File[] incomingFiles);
}
Then I've created an implementation Server representing the real object and a class ProxyServer representing the proxy. The Server furthermore has a factory method that creates a ProxyServer object but returns it as a ServerInterface.
The run-method on the proxy-object looks like this:
#Override
public void run(){
log(LogLevels.INFO, "server is running ...");
while( !stopped ){
try {
File[] incomingContent = scanIncomingDir();
moveIncomingFilesIfComplete(incomingContent);
updateHTML();
pause();
} catch (Exception e) {
logger.logException(e, new Timestamp(timestampProvider.getTimestamp()));
pause();
}
}
log(LogLevels.INFO, "server stopped");
}
The functions that are called within the try statement simply log something and then propagate the call to the real object. So far, so good. But now that I've implemented the run-method this way in the proxy object, the run-method in the real object becomes obsolete and thus, is just empty (same goes for the terminate-method).
So I ask my-self: is that ok? Is that the way the proxy pattern should be implemented?
The way I see it, I'm mixing up "real" and "proxy"-behaviour ... Normally, the real-server should be "stuck" in the while-loop and not the proxy-server, right? I tried to avoid mixing this up, but neither approaches were satisfying:
I could implement the run-method in the real object and then hand over the proxy object to the real object in order to still be able to log during the while-loop. But then the real object would do some logging, which is I tried to avoid by writing a proxy in the first place.
I could say, only Proxy-Server is Runnable, thus deleting run and terminate from the Interface, but this would break up the Proxy pattern.
Should I may be use another design? Or I am seeing a problem where there is none?
You're definitely thinking in the right way. You've hit upon an interesting notion.
Features like logging, as you've described, are an example of what we call cross-cutting concerns in Aspect Oriented programming.
A cross-cutting concern is a requirement that will be used in many objects.
. . therefore, they have the tendency to break object oriented programming. What does this mean?
If you try to create a class that is all about moving files from place A to place B, and the implementation of a method to do that first talks about logging (and then transactions, and then security) then that isn't very OO is it? It breaks the single responsibility principle.
Enter Aspect Oriented Programming
This is the reason we have AOP - it exists to modularize and encapsulate these cross-cutting concerns. It works as follows:
Define all the places where we want the cross-cutting feature to be applied.
Use the intercept design pattern to "weave" in that feature.
Ways we can "weave" in a requirement with AOP
One way is to use a Java DynamicProxy as you've described. This is the default in for example the Spring Framework. This only works for interfaces.
Another way is to use a byte-code engineering library such as asm, cglib, Javassist - these intercept the classloader to provide a new sub-class at runtime.
A 3rd way is to use compile-time weaving - to change the code (or byte-code) at compile-time.
One more way is to use a java agent (an argument to the JVM).
The latter two options are supported in AspectJ.
In Conclusion:
It sounds as though you're moving towards Aspect Oriented Programming (AOP), so please check this out. Note also that the Spring Framework has a lot of features to simplify the application of AOP, though in your case, given this is a school assignment, its probably better to delve into the core concepts behind AOP itself.
NB: If you're building a production-grade server, logging may be a full-blown feature, and thus worth using AOP. . in other cases its probably simple enough to just in-line.
You should use Observer pattern in this case:
The observer pattern is a software design pattern in which an object,
called the subject, maintains a list of its dependents, called
observers, and notifies them automatically of any state changes,
usually by calling one of their methods.
Your Observable will observe changes in directory, by time pooling, or as already was suggested here, with WatchService. Changes of directory will notify Observer which will take action of moving files. Both Observable and Observer should log their actions.
You shold also know that Observer pattern became a part of Java JDK by implementing java.util.Observable and java.util.Observer.
You can make your proxy aware of the real object. Basically your proxy will delegate the call to run method to the real implementation.
Before the delegation, the proxy first logs the startup. After delegation, the proxy logs the "shutdown":
// Snapshot from what should look like the run method implementation
// in your proxy.
public ServerInterfaceProxy(ServerInterface target){
this.proxiedTarget = target;
}
public void run(){
log(LogLevels.INFO, "server is running ...");
this.proxiedTarget.run();
log(LogLevels.INFO, "server is running ...");
}
This implementation can also be perceived as a Decorator pattern implementation. IMHO, I believe that to some extent (when it comes to implementation) Proxy and Decorator are equivalent : Both intercept/capture behavior of a target.
Look at Java 7's WatchService class.
Using Proxy behaviour for this is almost certainly overkill.

How to decouple a module which listens on a hibernate event from the entities themselves?

I have a layered web-application driven by spring-jpa-hibernate and I'm now trying to integrate elasticsearch (search engine).
What I Want to do is to capture all postInsert/postUpdate events and send those entities to elasticsearch so that it will reindex them.
The problem I'm facing is that my "dal-entities" project will have a runtime dependency on the "search-indexer" and the "search-indexer" will have a compile dependency on "dal-entities" since it needs to do different things for different entities.
I thought about having the "search-indexer" as part of the DAL (since it can be argued it does operations on the data) but even still it should be as part of the DAO section.
I think my question can be rephrased as: How can I have logic in a hibernate event listener which cannot be encapsulated solely in an entities project (since it's not its responsibility).
Update
The reason the dal-entities project is dependant on the indexer is that I need to configure the listener in the spring configuration file which is responsible for the jpa context (which obviousely resides in the dal-entities).
The dependency is not a compile time scope but a runtime scope (since at runtime the hibernate context will need that listener).
The answer is Interfaces.
Rather than depend on the various classes directly (in either direction), you can instead depend on Interfaces that surface the capabilities you need. This way, you are not directly dependent on the classes but instead depend on the interface, and you can have the interfaces required by the "dal-entities", for example, live in the same package as the dal-entities and the indexer simply implements that interface.
This doesn't fully remove the dependency, but it does give you a much less tight of a coupling and makes your application a bit more flexible.
If you are still worried about things being too tightly coupled or if you really don't want the two pieces to be circularly dependent at all, then I would suggest you re-think your application design. Asking another question here on SO with more details about some of your code and how it could be better structured would be likely to get some good advice on how to improve the design.
Hibernate supports PostUpdateEventListener and PostInsertEventListener.
Here is a good example that might suite your case
The main concept is being able to locate when your entity was changed and act after it as shown here.
public class ElasticSearchListener implements PostUpdateEventListener {
#Override
public void onPostUpdate(PostUpdateEvent event) {
if (event.getEntity() instanceof ElasticSearchEntity ) {
callSearchIndexerService(event.getEntity());
Or
InjectedClass.act(event.getEntity());
Or
callWebService(InjectedClassUtility.modifyData(event.getEntity()));
........
}
}
Edit
You might consider Injecting the class that you want to isolate from the project (that holds the logic) using spring.
Another option might be calling an outside web service that is not dependent on your code.
passing to it either the your original project object or one that is modified by a utility, to fit elasticsearch.

Getting to Guice created objects from dumb data objects

I've taken the plunge and used Guice for my latest project. Overall impressions are good, but I've hit an issue that I can't quite get my head around.
Background: It's a Java6 application that accepts commands over a network, parses those commands, and then uses them to modify some internal data structures. It's a simulator for some hardware our company manufactures. The changes I make to the internal data structures match the effect the commands have on the real hardware, so subsequent queries of the data structures should reflect the hardware state based on previously run commands.
The issue I've encountered is that the command objects need to access those internal data structures. Those structures are being created by Guice because they vary depending on the actual instance of the hardware being emulated. The command objects are not being created by Guice because they're essentially dumb objects: they accept a text string, parse it, and invoke a method on the data structure.
The only way I can get this all to work is to have those command objects be created by Guice and pass in the data structures via injection. It feels really clunky and totally bloats the constructor of the data objects.
What have I missed here?
Dependency injection works best for wiring services. It can be used to inject value objects, but this can be a bit awkward especially if those objects are mutable.
That said, you can use Providers and #Provides methods to bind objects that you create yourself.
Assuming that responding to a command is not that different from responding to a http request, I think you're going the right path.
A commonly used pattern in http applications is to wrap logic of the application into short lived objects that have both parameters from request and some backends injected. Then you instantiate such object and call a simple, parameterless method that does all magic.
Maybe scopes could inspire you somehow? Look into documentation and some code examples for read the technical details. In code it looks more less like that. Here's how this might work for your case:
class MyRobot {
Scope myScope;
Injector i;
public void doCommand(Command c) {
myScope.seed(Key.get(Command.class),
i.getInstance(Handler.class).doSomething();
}
}
class Handler {
private final Command c;
#Inject
public Handler(Command c, Hardware h) {
this.c = c;
}
public boolean doSomething() {
h.doCommand(c);
// or c.modifyState(h) if you want c to access internals of h
}
}
Some people frown upon this solution, but I've seen this in code relying heavily on Guice in the past in at least two different projects.
Granted you'll inject a bit of value objects in the constructors, but if you don't think of them as value objects but rather parameters of the class that change it's behaviour it all makes sense.
It is a bit awkward and some people frown upon injecting value objects that way, but I have seen this in the past in projects that relied heavily on Guice for a while and it worked great.

Categories

Resources