Application design - Updating domain object - java

I would like to improve the design of some part of my application. It is a swing application in which the user interface is updated by data received from a server (TCP/UDP). At the moment i pass my domain object (POJO) to the constructor of the class the will connect with the server, receive and send data, and directly use getter and setter method.
public static void main(String[] args) {
TcpClient client = new TcpClient(server, port, domainModel);
}
public class TcpClient {
public void connect() {
// Code to create the socket and connect to the server.
new Thread(new TcpProtocol(socket, domainModel)).start();
}
}
I 'm using some sort of Factory class inside the TcpProtocol class to create the right object.
I would like to decouple my domain object from the network programming part. Is there some common pattern to use for this ? I was thinking about DAO and Value Object, commonly used for JavaEE applications. Those are the only one i see, but if someone has better proposition please let me know.
Thank you.

As a general rule I consider non-trivial code in the constructor to be a design smell since it complicates inheritance and other forms of extensibility.
If you do not need the object to update itself from the network after it is created, then you can use a Factory to create your POJO. I tend to avoid ValueObjects unless you are wrapping something with very little data like currency/dates otherwise you will end up with a bunch of getters/setters.
If you need the object to access the network during its use, then you can make it a Proxy and pass in a DAO that handles all the network code. For testing you pass in a Mock/Stub instead.

A start to reaching your goal would be to remove the network access code from your constructor (I'm assuming you have one class that contacts the network and you're passing your POJO to its constructor). You would instead create a utility that contacts the network.
To instantiate the correct object type from your data stream, you might consider creating a Factory that knows how to adapt the stream to specific object types.

Maybe using the java.io ObjectInputStream and ObjectOutputStream might be a simple way to do this since it does not depend on the class of the object transferred?

What i would suggest to do is apply the Observer pattern. You might also need to apply the Mediator pattern along with your Observer - but check carefully if your design
warrants this kind of complexity.
The idea behind the observer is that your UI code "listens" for changes in the presented model. When changes take place (presumably from your network-bound code) an event is fired and your UI is thus notified in order to update itself accordingly,

Related

Port & Adapter Pattern - invoke multiple implementation of same output port

I have some doubt about how implement a simple scenario for a my style exercises following the Hexagonal architecture or Port & Adapter Pattern.
I have a UseCase (or service) that has to send a Contact (received from a contact form) to an external API service.
public class SendContactUseCase{
//output port interface
private final SendContact sendContact;
public ServiceLayer(SendContact sendContact) {
this.sendContact = sendContact;
}
public void sendContact(ContactRequest req){
sendContact.send(req);
}
}
So I have create an output port with a method send(ContactRequest req) after that I have implemented this interface as a driven adapter where I put the codes for the communication with the API
//driven adapter
public class SendContactToAPIAdapter implements SendContact {
//private final PossibleAPILib possibleAPIlib...;
#Override
public boolean send(ContactRequest req) {
//HERE the code to communicate with API
}
}
Here my doubt, what if at a later moment comes the need to send the "Contact" also to another channel, for example as XML attachment to a specific email address.
If I have understood correctly the Port & Adapter pattern to hide the infrastructure "logic" to the UseCase I should implement a new driven adapter from the same Port in order to inject the correct adapter in the UseCase.
public class SendContactXMLAdapter implements SendContact
But if I'd should invoke both the adapater? Beacause I have to send the contact to the both systems?
Should I to create a third adapter where hide the logic to call both systems?
I hope I've been clear
Thanks folks
Create a sample java project for a simple use case
The answer depends on what you actually want to accomplish.
To me, your anticipation of the 'need to send the "Contact" also to another channel' sounds like an additional feature of your business logic.
Based on that assumption, I would implement two separate port/adapter pairs, one for the API and one for XML. Your use case can then decide which ports to call.
This diagram visualizes what I mean: Component Architecture
If you really always want to send the contact to the API and export it as XML you could leave your use-case untouched and just extend the implementation of your SendContactToAPIAdapter to do both. But you should then also consider renaming it.
public interface ContactRegisterer{
public void registerContact(Contact contactToRegister) throws ContactRegisterException;
}
you could use this interface[represents a port which is used by more higher level logic of your application] so that the location of where to save the contact and how to save it could be changed independently from the client. This interface could be used to register contact to a single but different destinations, or to multiple and different destination. For instance, you could register to a file, a database, a service or all of them.
When you register to a single destination, all you need is to give a different implementation of the interface for registering to that destination.
When you register to multiple destinations, you could use Decorator design pattern. (Create a wrapper that implements the interface and also contains different objects implementing the same interface. The wrapper is given to the client(have the same interface, hence the client is not aware of the fact that it is given a wrapper), the wrapper in turn could use multiple threads for registering to each destination or use a for loop within a thread)
Another alternative is to use A Modified Version Of Chain of Responsibility pattern. In this pattern, you chain multiple(open ended) instances of the interface and every instance call the next after it is done registering to its destination.
It depends if the change is a technical change or a business logic change.
The ports and adapters architecture allows you to change the adapters without changing the Core of the application. If you have tests that validate your business logic, as you should, you'll see that you can swap adapters, everything will work fine and you won't have to change your Core tests. In this case, you can have the two adapters and configure one or the other based on some setting, or as you say, have an adapter that basically calls the other two.
On the other hand, if your business logic requirements change (depending on some business rule you have to send the contact to A or to B), you'll notice that you'll have to change your tests to verify the new requirements. In that case, your Core will define a different Port that will be more suited to the new business logic.

How to correctly implement communication between Java classes

I'm a beginner in Java programming and I'm currently working on an app with more complex class structure and a GUI. This might be a stupid questions, but it is very hard to google, so I'm asking here.
I have a main class, looking like this:
package app;
public class App {
private FirstClass fc;
private SecondClass sc;
public App () {
fc = new FirstClass ();
sc = new SecondClass ();
// ... code continues ...
}
}
Say the SecondClass is defined outside of this .java file (like GUI forms are). Is there a way for me to access the "fc" instance (or other member variables of the App instance) from the "sc" instance (without passing the "this" pointer)? Something like:
class SecondClass {
public void someMethod() {
getWhoeverCreatedThisInstance().fc.getSomeData();
// ... code continues ...
}
}
And if not, what am I doing wrong? Should I design this differently? Maybe setting the "fc" as static? But what if I want more of my app's classes to communicate with each other, should I make them all static? What would be the point of having something non-static then? I could pass the "this" pointer of "App" or "fc" instance in the constructor of "SecondClass", but that solution just seems non-elegant when the number of classes that need this behavior rises.
Any ideas? Thanks in advance!
My suggestion is to implement a callback system with interfaces. Each of your classes communicating with each other should implement these.
The classes should Register to the creating class.
Then they can call a method in the creating class which invokes the interface method of each registered class and passed the data this way.
This SO answer might help
https://stackoverflow.com/a/18279545
If you want to develop GUI applications, you should really get into the basic concepts. This can be very time-consuming, but it is necessary, otherwise you will encouter strange behaviour. I will just give you a basic understanding to answer your question.
You think of simple console applications, where you usually have a single thread and passing around objects is valid. With multiple threads, this is fatal, even with static variables. Each variable or object can be modified concurrently and the other thread may not be able to 'see' the changes in time. This is a complex matter, since there are also caches and separate stacks for each thread. In short, fc may not always be synchronized in App and sc, therefore reads and writes may be inconsistent.
What to do now? Learn the concepts of GUI programming. Often you do not even have to share objects for simple things. If a GUI control triggers an action, use a Listener, look here. If you want to access a database for example, then just make a new connection object for each request or button click, whatever. This is simple to start, add complexity later.
A simple variant to share objects is to use the synchronized keyword, which ensures that a method or a field is only accessed by one thread at a time. Here is an example. Also look at thread-safe data structures provided by Java (java.util.concurrent).
For advanced purposes you would have a separate thread and you would connect them with Sockets to pass messages or data.

Proxy pattern concrete class hiding implementation details

I have been reading about java proxy pattern and invocation handler and everywhere it is seen that the concrete class construction is available to the client.
For example,
//TwitterService service = (TwitterService) SecurityProxy.newInstance(new TwitterStub());
TwitterService service = new TwitterStub();
System.out.println(service.getTimelinePosts("abc"));
User can create an instance of TwitterStub directly and access the methods. I was wondering if there was a way of not exposing the or avoiding the construction of the concrete class via the client ?
Is there a better way ?
As the GoF puts it, the intent of the proxy pattern is "to provide a surrogate or placeholder for another object to control access to it".
So, in your specific case what happens is that you're creating a particular proxy instance directly. And that's fine as long as you (as a client) know that you want a particular type of proxy object.
If what you want is a level of indirection, you can use an Abstract Factory Pattern that return different types of proxy objects. But so far, the reason of proxy objects is to act on behalf of other objects.
As a side note, proxies are useful when you have objects that are expensive to create, but you don't want to necessarily cripple main application function due to such expense. For example, suppose you have a document with 1000 images. You can use proxies for them, and only load them when stricly needed (i.e. when they are in visible view), and you can still load the full document really fast without the overhead of reading 1000 images at once.

Is it possible create a single dynamic proxy that can add functionality to any concrete class?

I'll give a brief overview of my goals below just in case there are any better, alternative ways of accomplishing what I want. This question is very similar to what I need, but not quite exactly what I need. My question...
I have an interface:
public interface Command<T> extends Serializable {}
..plus an implementation:
public class EchoCommand implements Command<String> {
private final String stringToEcho;
public EchoCommand(String stringToEcho) {
this.stringToEcho = stringToEcho;
}
public String getStringToEcho() {
return stringToEcho;
}
}
If I create another interface:
public interface AuthorizedCommand {
String getAuthorizedUser();
}
..is there a way I can implement the AuthorizedCommand interface on EchoCommand at runtime without knowing the subclass type?
public <C extends Command<T>,T> C authorize(C command) {
// can this be done so the returned Command is also an
// instance of AuthorizedCommand?
return (C) theDecoratedCommand;
}
The why... I've used Netty to build myself a very simple proof-of-concept client / server framework based on commands. There's a one-to-one relationship between a command, shared between the client and server, and a command handler. The handler is only on the server and they're extremely simple to implement. Here's the interface.
public interface CommandHandler<C extends Command<T>,T> {
public T execute(C command);
}
On the client side, things are also extremely simple. Keeping things simple in the client is the main reason I decided to try a command based API. A client dispatches a command and gets back a Future. It's clear the call is asynchronous plus the client doesn't have deal with things like wrapping the call in a SwingWorker. Why build a synchronous API against asynchronous calls (anything over the network) just to wrap the synchronous calls in an asynchronous helper methods? I'm using Guava for this.
public <T> ListenableFuture<T> dispatch(Command<T> command)
Now I want to add authentication and authorization. I don't want to force my command handlers to know about authorization, but, in some cases, I want them to be able to interrogate something with regards to which user the command is being executed for. Mainly I want to be able to have a lastModifiedBy attribute on some data.
I'm looking at using Apache Shiro, so the obvious answer seems to be to use their SubjectAwareExecutor to get authorization information into ThreadLocal, but then my handlers need to be aware of Shiro or I need to abstract it away by finding some way of mapping commands to the authentication / authorization info in Shiro.
Since each Command is already carrying state and getting passed through my entire pipeline, things are much simpler if I can just decorate commands that have been authorized so they implement the AuthorizedCommand interface. Then my command handlers can use the info that's been decorated in, but it's completely optional.
if(command instanceof AuthorizedCommand) {
// We can interrogate the command for the extra meta data
// we're interested in.
}
That way I can also develop everything related to authentication / authorization independent of the core business logic of my application. It would also (I think) let me associate session information with a Netty Channel or ChannelGroup which I think makes more sense for an NIO framework, right? I think Netty 4 might even allow typed attributes to be set on a Channel which sounds well suited to keeping track of things like session information (I haven't looked into it though).
The main thing I want to accomplish is to be able to build a prototype of an application very quickly. I'd like to start with a client side dispatcher that's a simple map of command types to command handlers and completely ignore the networking and security side of things. Once I'm satisfied with my prototype, I'll swap in my Netty based dispatcher (using Guice) and then, very late in the development cycle, I'll add Shiro.
I'd really appreciate any comments or constructive criticism. If what I explained makes sense to do and isn't possible in plain old Java, I'd consider building that specific functionality in another JVM language. Maybe Scala?
You could try doing something like this:
Java: Extending Class At Runtime
At runtime your code would extend the class of the Command to be instantiated and implement the AuthorizedCommand interface. This would make the class an instance of AuthorizedCommand while retaining the original Command class structure.
One thing to watch for, you wouldn't be able to extend any classes with the "final" keyword.

Some questions about OOP in Java

I have a GUI class with a menu of buttons and textfields. Depending on what choices that is made in the menu and the input, methods in the GUI class are calling methods in the Logic class to send the input and create new objects of Customer class and Account class and so on.
To be able to communicate between the GUI- and the Logic class, I first create an object of the Logic class and I do that inside the GUI class, since it's here I have my main method. It this the best way to do it? Do I need some kind of reference variable between GUI- and Logic class or just use the reference when the object was created in the beginning of the GUI class? I guess to be able to communicate with a class, it must be an object first!? Thanks!
Logic logic = new Logic();
logic.addCustomer(name, number);
Ideally you shouldn't directly create the logic class.
You should break down the functionality into a number of small classes, each of which satisfy a responsibility.
A simplistic way would be for the GUI class to create listeners which listen to the user events. In response the to the use event they fire events that your logic registers itself for. Then when the event is received the logic class can perform the functionality.
You should read about observer pattern, event driven design...
You can read about event driven programming here http://en.wikipedia.org/wiki/Event-driven_programming .
I would instantiate the Logic class outside the GUI, but pass it as an argument to the GUI constructor. It's nearly equivalent to what you are already doing, but I think it makes it clearer that the GUI uses a Logic object. Also, it's possible that Logic does some other things before/after the GUI starts/closes; it might not be the case now, but it could be true in the future if you extend your program.
Many other answers tell you to look at MVC, but that might be overkill for your project. It can decrease complexity for a large project, but increase it for a small one.
EDIT:
Logic login = new Logic();
...
MyGUI gui = new MyGUI(logic);
...
I would suggest you do some researches on the MVC architecture. Your GUI (view) shouldn't interact directly with your model (logic). Implement a controller that will get the "signals" from your view and will be in charge to create your "logic objects" and work with them.
You can create on object of type Logic in your main and store a reference of the object in your Window object - so you can access your Logic object as long as the window exists.
You should look up the Singleton design pattern for such trivial scenarios.
By default, Java uses Reference variables. Hence, if you instantiate your object in GUI class, make sure you send the object via method calls to your processing class.
Alternatively, you can look into singleton classes, which will return only one instance of the class. Inside that class, instantiate all the objects that you will need globally, and re-use that instance throughout your program.
Generally you can. If your application is very simple.
But this approach is not scalable. As your application gets more complex it became much harder for development and support. Try to consider Model–view–controller pattern to define a best way for your design. (according to your nick name I'll take a risk to propose an alternative link)

Categories

Resources