Messaging: Lots of RemoteServices methods or Unique message builder/interpreter? - java

Hey guys,
I'm using GWT to code a simple multiplayer board game.
And while I was coding the question came up to my mind:
At first I though my client could simply communicate with the server via RemoteServices calls, so if a client wanted to connect to a game he could do as follows:
joinGame (String playerName, String gameName)
And the server implementation would do the necessary processing with the argument's data.
In other words, I would have lots of RemoteService methods, one for each type of message in the worst case.
I thought of another way, which would be creating a Message class and sub-classing it as needed.
This way, a single remoteService method would be enough:
sendMessage (Message m)
The messages building and interpreting processing too would be done by specialized classes.
Specially the building class could even be put in the gwt-app shared package.
That said,
I can't see the benefits of one or another. Thus I'm not sure if I should do one way or another or even another completely different way.
One vs other, who do you think it is better (has more benefits in the given situation)?
EDIT: A thing I forgot to mention is that one of the factors that made me think of the second (sendMessage) option was that in my application there is a CometServlet that queries game instances to see if there is not sent messages to the client in its own message queue (each client has a message queue).

I prefer the command pattern in this case (something like your sendMessage() concept).
If you have one remote service method that accepts a Command, caching becomes very simple. Batching is also easier to implement in this case. You can also add undo functionality, if that's something you think you may need.
The gwt-dispatch project is a great framework that brings this pattern to GWT.

Messaging takes more programmer time and creates a more obfuscated interface. Using remote service methods is cleaner and faster. If you think there are too many then you can split your service into multiple services. You could have a service for high scores, a service for player records, and a service for the actual game.
The only advantage I can see with messaging is that it could be slightly more portable if you were to move away from a Java RPC environment but that would be a fairly drastic shift.

Related

What does the client do in Command Pattern?

I am reading the headfirst design patterns book.
I observe that the client is shown analogous to a hotel customer, who creates an order(command) object, the waitress(invoker) picks it and calls its execute() method which in turn calls the chef's cook() method(chef=receiver)
In the command pattern class diagram, I can see client is associated with Receiver as well as the ConcreteCommand class. I am unable to get the example because in real world, a customer is not supposed to know about the cook and set the instructions for him. Other concern is that in the command pattern class diagram, I observe that Client is not shown associated with Invoker, but in the attached java program I can see the Invoker reference in the Client class.
Totally confused about what Client module does in the command pattern. Clear about the rest 4 modules.
Read this: http://www.oodesign.com/command-pattern.html
Client creates a ConcreteCommand object and sets its receiver [...] The Client asks for a command to be executed.
It even has sample code that show what the client does:
The client creates some orders for buying and selling stocks (ConcreteCommands). Then the orders are sent to the agent (Invoker). [...]
public class Client {
public static void main(String[] args) {
StockTrade stock = new StockTrade();
BuyStockOrder bsc = new BuyStockOrder (stock);
SellStockOrder ssc = new SellStockOrder (stock);
Agent agent = new Agent();
agent.placeOrder(bsc); // Buy Shares
agent.placeOrder(ssc); // Sell Shares
}
}
You've stumbled upon the challenge with demonstrating design patterns with analogy, by a single concrete example, or with object diagrams. Except for very simple patterns, the concepts and examples usually don't map perfectly to all useful instances of the pattern.
I highly recommend that you pick several sources to learn any of the more complex design patterns. Every explanation is going to have strengths and weaknesses, and you'll probably get a more accurate picture if you take several viewpoints into account. There are plenty of free sources available on the Internet, so you probably don't need to buy additional books (except, eventually, the original Design Patterns book, for reference purposes).
What isn't clear in the diagram is that the Client, the Invoker, and the Receiver are abstract concepts, and don't have a single form that always applies in every case. In any particular implementation of the command pattern, most of these roles are going to be present (except maybe the Receiver - it is possible that the command is self-contained). You may even be able to point out a specific bit of code that maps to each of these roles, but it's going to map differently in every application. It may even map differently in separate parts of the same application.
There are parts of the diagram you shared that I have problems with, because they are not always true. The Client might not directly access or even know about the Receiver. The Client might also not know about specific ConcreteCommand objects. The Client might know how to ask for an instance of a command, and it might know some information that helps pick the right command. However, the client might in some cases be oblivious to which ConcreteCommand object was executed, especially if you combine the command pattern with the AbstractFactory pattern.
in real world, a customer is not supposed to know about the cook and set the instructions for him
Analogies and models tend to break down or become confusing when you compare them strictly to reality. It is best to try to figure out what the model is trying to accomplish, and which possible interpretation of reality that the model is trying to account for.
Also, not all models/analogies are any good :) Sometimes they don't actually get the job done.
I observe that Client is not shown associated with Invoker
This is perfectly valid in some implementations of the pattern. The code that eventually calls execute() may not be the same code that is capable of accepting actions.
The diagram may show a single box, but in the restaurant analogy, the waiter, the cooks, the busboys, the host, the cashier, etc, are all a part of that Invoker role.
The problem with the diagram is that the client eventually has to pass the command off to the invoker. The invoker itself might have a way to accomplish this, or there may be some sort of system in between (like a command queue). Either way, in their explanation, the invoker role handles both things, and the client must therefore know about the invoker.
Finally:
What does the client do in Command Pattern?
The Client is responsible for knowing that it wants a command to be done
The Client is responsible for knowing how to pick which command gets done, and get an instance of it (even if the client delegates the actual construction of that ConcreteCommand to some other part of the system)
The Client is responsible for knowing how to pass off a command so that it will eventually be invoked (passing it to some object in the Invoker role, even if that command eventually gets passed off to some other object that actually calls execute())
The Client is responsible for actually handing off the command to the Invoker (whether it is directly handed off, or passed off to some intermediate part of the system first)
So the idea of a client is in opposition to the idea of a server. (for get the restaurant metaphor for a minute). The server is the centralized application, the client is the interface presented on a users machine. The client machine or GUI signals wither a receiver (middle man) or your program directly to make things happen.
I hope this makes things a little clearer.

Observer Pattern VS Owner Referencing. Which is more correct? (Java)

Within Java you can create an Observer-Observable set of classes in which the Observable can call the Observer. You can also in java explicitly reference an owning class instance in a child instance of another class and call the owning class instance's public functions.
Which is the better approach to take? Which is more beneficial in different scenarios, one example being Multi-Threading?
The Observer Pattern should be used whenever you don't know or don't care who is observing you. This is the key-concept in event-driven programming. You don't have any control of who is observing or what they do when you broadcast your events. Like you already mentioned in your comments, this is great for decoupling classes.
An example of a usage could be in a plugin-architecture:
You write a basic mail-server that broadcasts whenever a mail is received. You could then have a spam-plugin that validates the incoming mail, an auto-reply service that sends a reply, a forward service that redirects the mail and so on. Your plain mail server (the observable) doesn't know anything about spam, replies or forwarding. It just shouts out "Hey, a new mail is here" not knowing if anyone is listening. Then each of the plugins (the observers) does their own special thing, not knowing anything about each other. This system is very flexible and could easily be extended.
But the flexibility provided by the Observer Pattern is a two-edged sword. In the mail-server example, each plugin handles the incoming mail in total isolation from each other. This makes it impossible to setup rules like "don't reply or forward spam" because the observers doesn't know about each other - and even if they did, they wouldn't know in what order they are executed or has completed. So for the basic mail-server to solve this problem, It'll need to have references to the instances that does the spam/reply/forward actions.
So the Observer Pattern provides flexibility. You could easily add a new anti-virus plugin later, without having to modify your plain mail server code. The cost of this flexibility is loss of control of the flow of actions.
The reference approach gives you total control of the flow of actions. However you would need to modify your plain mail server code if you ever need to add support for an anti-virus plugin.
I hope this example gives you some ideas of the pros and cons of each approach.
In regards to multi-threading, one approach isn't favorable over the other.

Pattern/Best practice for updating objects on server from multiple clients

I have a general question about a best practice or pattern to solve a problem.
Consider that you have three programs running on seperate JVMs: Server, Client1 and Client2.
All three processes make changes to an object. When the object is changed in either client, the change in the object (not the new object) must be sent to the server. It is not possible just to send the new object from the client to the server because both clients might update the object at the same time, so we need the delta, and not the result.
I'm not so worried about reflecting changes on the server back to the clients at this point, but lets consider that a bonus question.
What would be the best practice for implementing this with X amount of processes and Y amount of object classes that may be changed?
The best way i can think of is consistently using the Command pattern to change the object on the client and the server at the same time, but there has to be a better way?
One of the possible ways to solve that is the Remote Method Invocation system in Java. Keep all the data values on the Server, then have the clients use remote calls to query them.
This would however require some smart caching to reduce the amount of pointless calls. In the end you would end up with something similar to the Command Pattern.
Modern games try to solve this issue with something I'd call an Execute-Then-Verify pattern, where every client has a local copy of the game world, that allows him to come to the same conclusion for each action as the server would. So actions of the player are applied to the local copy of the game world assuming that they are correct, then they are sent to the server, which is the ultimate instance to either accept that or revoke it later on.
The benefit of this variant of local caching is, that most players do not experience much lag, however in the case of contradictory actions they might experience the well-known roll-backs.
In the end it very much depends on what you are trying to do and what is more important for you: control over actions or client action flow.

How many GWT services

Starting a new GWT application and wondering if I can get some advice from someones experience.
I have a need for a lot of server-side functionality through RPC services...but I am wondering where to draw the line.
I can make a service for every little call or I can make fewer services which handle more operations.
Let's say I have Customer, Vendor and Administration services. I could make 3 services or a service for each function in each category.
I noticed that much of the service implementation does not provide compile-time help and at times troublesome to get going, but it provides good modularity. When I have a larger service, I don't have the modularity as I described, but I don't have to the service creation issues and reduce the entries in my web.xml file.
Is there a resource issue with using a lot of services? What is the best practice to determine what level of granularity to use?
in my opinion, you should make a rpc service for "logical" things.
in your example:
one for customer, another for vendors and a third one for admin
in that way, you keep several services grouped by meaning, and you will have a few lines to maintain in the web.xml file ( and this is a good news :-)
More seriously, rpc services are usually wrappers to call database stuff, so, you even could make a single 'MagicBlackBoxRpc' with a single web.xml entry and thousands of operations !
but making a separate rpc for admin operations, like you suggest, seems a good thing.
Read general advice on "how big should a class be?", which is available in any decent software engineering book.
In my opinion:
One class = One Subject (ie. group of functions or behaviours that are related)
A class should not deal with more than one subject. For example:
Class PersonDao -> Subject: interface between the DB and Java code.
It WILL NOT:
- cache Person instances
- update fields automatically (for example, update the field 'lastModified')
- find the database
Why?
Because for all these other things, there will be other classes doing it! Respectively:
- a cache around the PersonDao is concerned with the efficient storage of information to avoid hitting the DB more often than necessary
- the Service class which uses the DAO is responsible for modifying anything that needs to be modified automagically.
- To find the database is responsibility of the DataSource (usually part of a framework like Spring) and your Dao should NOT be worried about that. It's not part of its subject.
TDD is the answer
The need for this kind of separation becomes really clear when you do TDD (Test-Driven Development). Try to do TDD on bad code where a single class does all sorts of things! You can't even get started with one unit test! So this is my final hint: use TDD and that will tell you how big a class should be.
I think the thing to optimize for is that you can accomplish a result in one round trip to the server. I have an ad-hoc collection of methods on my service object, one for each situation the client finds itself in when it has to get something done. You do not want the client to RPC to the server several times in a row while the user is sitting there waiting.
REST makes things orthogonal, but orthogonality has a cost: there is a reason that the frequently used verbs in languages are irregular. In terms of maintaing clean orthogonal structure to your app, make sure your schema is well-designed. That is where each class should have semantics orthogonal to that of the other classes. When the semantics of each RPC call can be stated cleanly in the schema there will be no confusion as to what they mean, even if they aren't REST-fully ideal.

Should sockets for TCP/IP etc. be kept in a separate class? (Java)

I don't think I need to post my code (there's lots of it) but I'm happy to if prompted.
I am creating a distributed racing game in Java which currently has JFrame, JPanel and Car classes. I'm seeking the best way to implement the next stage which is the distributed part - I'm using TCP/IP rather than UDP as this is basically part of the requirements so there's no need to comment on that.
So I'm questioning client and server sockets, streams and buffered readers etc.
For, I guess you could say, best practice - I'm wondering if I should start the implementation by having it all separate from main for elegance and possibly extensibility etc.
In general you are looking to use OO for separation of concerns. This means you divide what needs to be done in several manageable chunks. Then you decide on a clean understandable interface for each chunk, which hides the implementation details that aren't relevant to the user of the class.
In your case the reasoning could go something like this ( but it is entirely up to the problem you have).
One class is handling the connecting/disconnecting and returns an simple object that represents a message sent or received. This class knows nothing or little about the contents sent over the line, but it knows how to set up a connection and what to do with a disconnect.
The next class in line converts the simple message objects to useful objects with convenience methods that are easy to handle.
Another class is responsible for putting these objects to effect.
Of course when one of these tasks gets too big you can split them up even further.
In most cases this will result in one object managing one socket.

Categories