I am developing a web distributed application to let any user to play the Klondike (solitaire) game. I want to develop a API REST but I am not sure how the resources URL should look like.
At the server, I have the 'game', 'stock', 'waste', 'tableau', 'foundation' classes among others. The game class has the method moveFromStockToWaste, moveFromTableauToTableu... which implements the movements of the game.
What I have read about REST API is that the resources URL should look like a hierarchy of nouns while the operations (verbs) over this nouns are the HTTP methods (GET, PUT, POST, PATCH).
I am not sure if the way to move a card from stock to waste via API REST should look like this though moveFromTableauToTableau resource is a verb and not a noun:
UPDATE /player/{playerId}/game/{gameId}/moveFromTableauToTableau
Other way I have though is having this tableau piles cards resources:
URL: /player/{playerId}/game/{gameId}/TableauPile/1/
than in turn have resources like the number of not upturned cards and the upturned cards (all the information needed about the tableaus).
Then update this tableau pile resource by deleting the last card:
DELETE /player/{playerId}/game/{gameId}/TableauPile/1/upTurnedCard/3
And then put the card deleted in the target passing the new card suit and value:
POST /player/{playerId}/game/{gameId}/TableauPile/3/upTurnedCard
But this way the REST API would let to move a card from the tableau to the waste and this is not a valid movement.
I always think designing a REST API as a pretty uneasy task.
The second approach seems cleaner in naming convention terms, but I think you should never compromise the integrity of your targeted system to be compliant with such things. As you allow making one atomic operation in two http calls, it is in fact no longer atomic and you expose your system to unpredictable state in case of network failure or if any call fail for some reason. Avoid this kind of problem must be the top priority.
One idea could be thinking moves in terms of moves collection. So for a game you have a moves ressources. And then you can refine the move nature with some additional request parameters such like
POST/players/{playerId}/games/{gameId}/moves?type=TABLEAU_TO_TABLEAU
Body:
{
"src": "stock",
"dest": "waste"
}
This way you should have enough flexibilty to handle the different types of move.
Besides, may I suggest you to use plural form for resource naming :
player -> players
game -> games
so
GET /players naturally means give me all values of the player resource
GET /players/1 means give me the player of the players resource with the restriction playerId=1
I am developing a web distributed application to let any user to play the Klondike (solitaire) game. I want to develop a API REST but I am not sure how the resources URL should look like.
Oracle: how would you implement this as a website?
At the server, I have the 'game', 'stock', 'waste', 'tableau', 'foundation' classes among others. The game class has the method moveFromStockToWaste, moveFromTableauToTableu... which implements the movements of the game.
One important thing to realize is that the classes in your implementation don't matter; REST is about manipulating documents, the changes that happen to the game are side effects of manipulating the "documents".
In other words, the REST API is a mask that your game wears so that it looks like a web site.
See Jim Webber's talk DDD In the Large.
Klondike is effectively a state machine; any given tableau has some limited number of legal moves to make, each of which takes you to a new position.
So one way you might model the API is a representation of the tableau plus affordances (links) for each move, and the game progresses from one state to the next as you follow the links that describe a possible legal move.
There are "only" 8*10^67 or so deals to worry about, and for each of them you effectively have a graph of all of the reachable positions, and order them by traversal order, and then just link them all together.
/76543210987654321098765432109876543210987654321098765432109876543210/0
/76543210987654321098765432109876543210987654321098765432109876543210/1
/76543210987654321098765432109876543210987654321098765432109876543210/2
/76543210987654321098765432109876543210987654321098765432109876543210/3
And so on.
It's not an impossible arrangement, although it may be impractical, and since the URL describes the entire state of the game, the player has access to hidden state.
I'd suggest first trying this approach on something less complicated, like tic-tac-toe.
Hiding the state is relatively straight forward, because the mapping of the current game to a specific seed can be done on the server. That is, you send a POST to the start game end point, and that generates some random identifier, and maps the random identifier to a seed position, and off you go.
But a potential problem in this design is that HTTP is a stateless protocol; there's no way for the server to "know", when the player requests GET /games/000/152, that the client was previously in a position that could legally move to position 152. You can make the URI hard to guess, but that's about it.
What you likely want is the ability to ensure that the moves made by the player are legal, which means that the server needs to be tracking the current state of the game, and the player gets a view of the open information only.
The simplest HTML model of this would have the representation of the game show the information that the player is allowed, and a form with a list of the legal moves. The player selects one move and submits the form, which is a POST back to the game resource (directly back to the same resource, because we want the cache invalidation properties). Your implementation could then check that the received move is legal, refresh its own local state, and send an appropriate response.
That's the basic pattern we should be considering; GET the game, then send an unsafe request to modify the server's copy of the game.
The basic plan isn't all that different if you want to use a remote authoring approach. GET fetches a representation of the revealed information, the client makes legal edits to that representation, and PUTs the new representation to the same URL. The server verifies that the new position is reachable from the old position, and accepts the move, using its own copy of the hidden information to update the representation of the player's view.
(Pay careful attention to the meta data used in the response to PUT; the server is supposed to be communicating carefully whether the new representation is adopted as is, or if the server has transformed the proposed representation to make it consistent with the server's constraints).
You could, of course, also use PATCH to communicate the changes made to the representation by the client.
If messages were lost, or duplicated, the client's view and the server's view might not be aligned. So you may want to have your representation of the game include a clock/timer/turn number, so that the server can be certain that the players move is intended for the current state of the game.
EDIT As Roman notes, HTTP already has built into it the concept of validators, which allow you to lift data from your domain specific clock into the headers, so that generic components can understand and act appropriately to conditional requests
Another way of thinking about the game is to consider event sourcing; the client and the server are taking turns appending entries to a log, and the view of the game itself is computed by applying the events in the log. The client's moves would be limited to the set that manipulate the open information, the server's moves would reveal previously hidden information.
So you could use Atom Pub, or something very similar to it, to write new entries into the log. This in effect gives you two different representations of the game - the view, that shows you what you see when you look at the tableau, and the feed, which shows you the moves made to reach that point.
(If you squint, you'll see that this is really just a variation on "let the client pick a legal move".)
You could, I suppose, treat each of the elements in your domain model as a resource, and try to design an API to allow the client to manipulate those directly, but it isn't at all clear to me what benefit you get from that.
Related
I have a react-native application that populates pins on a map that have been submitted by users. The front end gets the corners of the window and then the back end goes through each pin to check if it falls within the boundary, and returns the ones that do.
This is taking too long on the backend and I want to ask the community for ideas, because I doubt I have the best one.
My idea is to store tables of pins grouped by quadrants, effectively a cache, and then I can in almost constant time return the pins from the quadrants involved.
Is there a simpler way to do this?
Maybe using NoSQL?
🙏🏻
A month later it seems geohashing is probably the best way, plus AWS has a library for automatically handling this with dynamodb. Apparently it takes the corners of the screen, lat/lon, and automatically returns the items from the DB in the view, in, I assume, constant time, since that's the whole point of geohashing, getting performance that works at scale..
https://www.npmjs.com/package/dynamodb-geo
https://aws.amazon.com/blogs/compute/implementing-geohashing-at-scale-in-serverless-web-applications/
Otherwise, using a geohashing library that is built for serving mobile apps likely exists.
We have multiple projects with multiple portlets and need to send an array of objects between them.
Our situation:
One of the porlets is like a "Master-portlet", it will be responsible for all the REST-calls and consume json-data and parse it to Java-Objects.
All the other portlets will receive an array of objects and show them to the user.
Our thoughts and solution:
We wanted to implement this by sending arrays of objects trough events. One of the "smaller" portlets will send an event to the "Master-portlet" and the "Master-portlet" will then answer with a new event and send the right array of objects back.
Our problem:
We dont know how to send arrays of objects trough events. Is this even possible?
Also we are not sure if this is the right way to solve this. Are events ment to send a bigger amount of data?
Is there a better solution for our case? Maybe it would be better to implement a database and all the portlets get the information from there?
Consider portlet events (and portlets) the UI layer of your application. Based on this, judge if the amount of data that you send back and forth makes sense or not. Also, if you closely couple the portlets, you're just hiding the fact that they can only function together - at least a questionable idea. You rather want them to react to common circumstances (events), but not rely on a specific source of events (master portlet) being available.
That being said: The more complex the data is that you send as payload of a JSR-286 event, the easier you run into classloading problems in cases where your portlets are in different webapplications. If you restrict yourself to Java native types (e.g. String, Map, etc) you will omit problems with the classloader.
Typically you want to communicate changes to the current context (e.g. new "current customer" selected - and an identifier) but not all of the particular data (e.g. the new customer's name and order history). The rest of the data typically comes through the business layer anyway.
That's not to say that you absolutely must not couple your portlets - just that my preference is to rather have them very loosely coupled, so that I can add individual small portlets that replace those that I thought of yesterday.
If you have some time, I've covered a bit of this in a webinar last year, I hope that this adds some clarification where I was too vague in this quick answer.
I'm creating a cricket manager stats game. I need to create a ball-by-ball simulation of the game. The game/ball outcome will be influenced by player stats and other external factors like weather or chosen tactics.
I've been reading around that most of the games can be implemented as a state machine, which sounds appealing to me, but because I'm a newbie at cricket I'm failing to envision this game as a state machine.
Should the Ball be a state machine or the match or the player or all 3. I'm also not sure how will i orchestrate this state machines (through events).
I'm also having hard time identifying the States and transitions. Any help would be greatly appreciated.
So here's what I understand from your question - Your cricket manager game will simulate a match ball by ball depending on player stats (bowler's skill/experience, batsman's skill/exp, fielding/wicketkeeping stats, so on...) and other related variables. From my understanding this will be more of an algorithmic engine rather than a visual representation of a cricket game.
Now answering your question, first of all, I don't believe you're looking at FSMs the right way. An FSM is a piece of code designed such that at any point in it's lifetime, it is in one of many possible states of execution. Each state can and usually has (that's the point of it) a different update routine. Also, each state can transition to another state upon predefined triggers/events. What you need to understand is that states implement different behaviour for the same entity.
Now, "most of the games can be implemented as a state machine" - Not "a" state machine but rather a whole nest of state machines. Several manager classes in a game, the renderer, gameplay objects, menu systems, more or less everything works off a state machine of its own. Imagine a game character, say a boxer, for the purpose of this example. Some states you'll find in the 'CBoxer'(?) class will be 'Blocking', 'TakingHit', 'Dodge', RightUpper', 'LeftHook' and so on.
Keep in mind though, that FSMs are more of a design construct - a way to envision the solution to the problem at hand. You don't HAVE to necessarily use them. You could make a complete game without a state machine(I think :) ). But FSMs make your code design really intuitive and straightforward, and it's frankly difficult to not find one in any decent sized project.
I suggest you take a look at some code samples of FSMs at work. Once you get the idea behind it, you'll find yourself using them everywhere :)
As a first step you should go through the rules of cricket and your model for the ball outcome to summarise how previous balls affect a given ball.
Then identify what you need to keep track of, and whether it is convenient to use a state machine to represent it. For example, statistics are usually not very convenient to keep track of as FSMs.
With that information in mind, you should be able to build a model. Information you need to keep track of might be either state machines or an internal value of a particular state. The interactions between balls will dictate the transitions and the events circulating from one machine to another.
I'm supporting a server for an online card game and while thinking about refactoring it into a better state I have found myself unable to decide what is a proper object model for my needs.
I have a Player class which has a lot of attributes. The first problem is just that - the class is too big. The second problem is that I don't know how to refactor it. I will list some of the attributes and issues with these.
Some attributes are very tightly bound to a player: nick, email, last login &c. These, I suppose, are to be kept directly in the player class and in the same table in the DB.
Now, some attributes are a little more difficult, like money and gold amount. The problem with these is that they are historically stored in a different table, there might be some more currencies later on and that they MUST be synched into the database at their own pace.
Third category of attributes are loosely coupled to the player, like status string, experience, achievements, statistics &c. These are stored in different tables in the DB and MUST be stored, retrieved, cached and synchronized at their own pace.
Note that one of the big problems here is that we have to implement relatively complex database synchronization schemes because we have a lot of online players and our game is soft-realtime and we have to make load on the DB as low as possible.
My questions are:
How to determine which attributes to store within a player class and which not to? Say, experience, nickname, money amount?
When one has some attributes that may be grouped together like (strength, agility, endurance, &c.) and (handItem, headItem, feetItem, weapon) when they should be grouped and when not?
What to do with complex database synchronization schemes? Make a separate model for each attribute that needs to be synched independently or make some DataManager classes to take them apart and work with them?
What to do with the need for a class to have several different "data representations" for external consumers? Like XML, Json, another XML for some external service, human-readable string, &c.
I'm sorry if my questions are bogus, I'm not really good at OOP design, I'm more an FP guy. And my English is not very good =).
There is no "limit" to what you can store in a player class. As long as it is concerning him and him only, it should be in his class. But one thing you should consider is to make several player classes. The idea is : if you don't need is, don't query it. You may have PlayerView_Small, PlayerBuying, PlayerFighting, PlayerSettings (depending on your game, they may not be fulfilling the exact same purpose)... This way for each "need" of info on a player, you only load the player data you need, and can handle it properly. Also, you may use inheritance if some class is only a more detailed version of the other.
If you are talking about the class, it may be in a sub-class PlayerAttributes of which an instance is contained into PlayerFighting and PlayerView_Detailed. In the database, it might be interesting to store it as a string (conveniently outputted by our class, and accepted in constructor), to avoid having too much fields, but you will lose the sorting ability. That's probably not a problem in our case, but might be in some others.
Blank for now, I don't understand where there is synchronization, will edit when informed.
In your PlayerViewDetailInfo(or in your PlayerAllData depending what you need), you place some methods such as ToXmlClient1(), ToJson(), ToHumanReadableString() (although that might be a bit confusing to the eye, you should consider HTML^^). The class having the method should be the class with the least (but sufficient to provide the answer) data. When requested, you load the Player... which has the method giving the correct output, and you write it directly in the response.
I've run into reoccuring problem for which I haven't found any good examples or patterns.
I have one core service that performs all heavy datasbase operations and that sends results to different front ends (html, silverlight/flash, web services etc).
One of the service operation is "GetDocuments", which provides a list of documents based on different filter criterias. If I only had one front-end, I would like to package the result in a list of Document DTOs (Data transfer objects) that just contains the data. However, different front-ends needs different amounts of "metadata". The simples client just needs the document headline and a link reference. Other clients wants a short text snippet of the document, another one also wants a thumbnail and a third wants the name of the author. Its basically all up to the implementation of the GUI what needs to be displayed.
Whats the best way to model this:
As a lot of different DTOs (Document, DocumentWithThumbnail, DocumentWithTextSnippet)
tends to become a lot of classes
As one DTO containing all the data, where the client choose what to display
Lots of unnecessary data sent
As one DTO where certain fields are populated based on what the client requested
Tends to become a very large class that needs to be extended over time
One DTO but with some kind of generic "Metadata" field containing requested metadata.
Or are there other options?
Since I want a high performance service, I need to think about both network load and caching strategies.
Does anyone have any good patterns or practices that might help me?
What I would do is give the front end the ability to request the presence of the wanted metadata ( say getDocument( WITH_THUMBNAILS | WITH_TEXT_SNIPPET ) )
Then this DTO is built with only this requested information.
Adding all the possible metadata is as you said, unacceptable.
I will surely stay with one class defining all the possible methods (getTitle(), getThumbnail()) and if possible it will return a placeholder when the thumbnail was not requested. Something like "Image not available".
If you want to model this like a pattern, take a look at the factory patterns.
Hope this helps you.
Is there any noticable cost to creating a DTO that has all the data any of your views could need and using it everywhere? I would do that, especially since it insulates you from a requirement change down the line to have one of the views incorporate data one of the other views uses
ex. Maybe your silverlight/flash view doesn't show the title itself b/c it's in the thumb now, but they decide they want to sort by it later.
To clarify, I do not necesarily think you need to pass down all of the data every time, but I think your DTO class should define all of them. Just don't fall into the pits of premature optimization or analysis paralysis. Do the simplest thing first, then justify added complexity. Throw it all in and profile it. If the perf is unacceptable, optimize and try again.