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

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.

Related

combined vs. separate backend calls

I try to figure out the best solution for a use case I'm working on. However, I'd appreciate getting some architectural advice from you guys.
I have a use case where the frontend should display a list of users assigned to a task and a list of users who are not assigned but able to be assigned to the same task.
I don't know what the better solution is:
have one backend call which collects both lists of users and sends them
back to the frontend within a new data class containing both lists.
have two backend calls which collect one of the two lists and send them
back separately.
The first solution's pro is the single backend call whereas the second solution's pro is the reusability of the separate methods in the backend.
Any advice on which solution to prefer and why?
Is there any pattern or standard I should get familiar with?
When I stumble across the requirement to get data from a server I start with doing just a single call for, more or less (depends on the problem domain), a single feature (which I would call your task-user-list).
This approach saves implementation complexity on the client's side and saves protocol overhead for transactions (TCP header, etc.).
If performance analysis shows that the call is too slow because it requests too much data (user experience suffers) then I would go with your 2nd solution.
Summed up I would start with 1st approach. Optimize (go with more complex solution) when it's necessary.
I'd prefer the two calls because of the reusability. Maybe one day you need add a third list of users for one case and then you'd need to change the method if you would only use one method. But then there may be other use cases which only required the two lists but not the three, so you would need to change code there as well. Also you would need to change all your testing methods. If your project gets bigger this makes your project hard to update or fix. Also all the modifications increase the chances of introducing new bugs as well.
Seeing the methods callable by the frontend of the backend like an interface helps.
In general an interface should be open for extension but closed on what the methods return and require. As otherwise a slight modification leads to various more modifications.

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.

How to apply static class in php

I am java and php programmer.
In java i can use static class/method so that anyone can use the same one time created class during run-time.
But for php how to do it since it is script based and only run while we refreshing the page?
My main objective is, I want to use syncronized class/method so that it wont clash while executing the PHP...
Need your help to give input.
Thanks
Update:
I am doing portal like multi level marketing(mlm)
Once register a member, we should pay bonus to the uplines
I don't want immidiately calculate the bonus because it is risky and could take some time to finish, so is is better just to register the member and show successfull.
My idea is, after registration, just invoke another class to run bonus with syncronized method so that the bonus calculation will not disturb by another registration.
Given that a php scripts runs from new every sinlge time a "static" class would not be very different from an ordinary class.
If you want to store some sort of state or preserve some data between runs of a php program then there are a number of options.
SESSION variables can be used to store data between requests from a single users as long as he keeps the session open.
COOKIES can be used to store data which persists between sessions as long as the user is using the same browser, on hte same machine and hasnt emptied the cookie jar.
memchached and similar packages can be used to store data and make it available to any php program on the server.
Databases are the most scalable solution as they will persist data between sessions, and between servers. There is some overhead involved is establishing connections and retrieving the data compared with the other solutions.
PHP is shared-nothing. Everything just lives for the Request. If you want to share information between Requests, you have to implement some additional technology layer that can do so. Or look into process control, shared memory segments and semaphores. The latter three are uncommon usage in PHP though. And all of the above will still be asynchronous.
To my knowledge, there is no way to update class Foo in one Request and have it change state immediately in a concurrent Request with PHP.

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

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.

Categories