How to communicate between object instances in a "has-a" relationship (Smalltalk)? - relationship

I have been programming in Smalltalk for quite some time, but yesterday I managed to confuse myself and cannot figure out or remember how to handle this.
I have two objects in a "has-a" relationship, therefore the child object (the one that is had) is not a subclass of the owner. I cannot figure out how to message the owner and pass it some information.
To make this more concrete, the owner is a Game object and the child object is a Turn. When the turn has been completed, I need to send the turnScore to the Game instance to be added to the Game's totalScore. But, in the Turn instance, I don't see how to have a handle back to the owning Game instance. Everything I try to code errors with "message not understood".
Please help me get back on track. This should be simple. Thanks.

Generally, and as in any other language, you will need a reference from the Turn object to the Game object (for example in an instance variable of Turn) if you want to send it a message. Or some other means through which the Turn object can obtain a reference to the Game (singletons, mediators, service registries, ...).
Initialization could be done as follows:
Game》newTurn
^ Turn new
game: self;
yourself
Turn》game: aGame
game := aGame.
Alternatively you could design the control flow so that the Game does not need to be called. The Game could ask the Turn for the score instead.
Another fancy approach would be to signal a ScoreNotification and handle and resume that in a method of the Game further up the call stack, if that fits the control flow. But "fancy" here probably means unnecessarily complicated.

Related

How to clear the whole MapSate state with only one call

I know that if I do mapState.clear() I will be able to clean all the values into the state for the specific key, but my question is: Is there a way to do something like mapState.clear() and clean all the states into the mapStates with just one call? will be something like mapState.isEmpty() it will say "true" because all the keys into the mapState were cleaned up, not just for the current key.
Thanks.
Kind regards!
Because we are talking about a situation with nested maps, it's easy to get our terminology confused. So let's put this question into the context of an example.
Suppose you have a stream of events about users, and inside a KeyedProcessFunction you are using a MapState<ATTR, VALUE> to maintain a map of attribute/value pairs for each user:
userEvents
.keyBy(e -> e.userId)
.process(new ManageUserData())
Inside the process function, any time you are working with MapState you can only manipulate the one map for the user corresponding to the event being processed,
public static class ManageUserData extends KeyedProcessFunction<...> {
MapState<ATTR, VALUE> userMap;
}
so userMap.clear() will clear the entire map of attribute/value pairs for one user, but leave the other maps alone.
I believe you are asking if there's some way to clear all of the MapStates for all users at once. And yes, there is a way to do this, though it's a bit obscure and not entirely straightforward to implement.
If you change the KeyedProcessFunction in this example to a KeyedBroadcastProcessFunction, and connect a broadcast stream to the stream of user events, then in that KeyedBroadcastProcessFunction you can use KeyedBroadcastProcessFunction.Context.html#applyToKeyedState inside of the processBroadcastElement() method to iterate over all of the users, and for each user, clear their MapState.
You will have to arrange to send an event on the broadcast stream whenever you want this to happen.
You should pay attention to the warnings in the documentation regarding working with broadcast state. And keep in mind that the logic implemented in processBroadcastElement() must have the same deterministic behavior across all parallel instances.

REST API for a game

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.

Caliburn.Micro return result from child view model

So I have a ViewModel which contains logic to select a person from a list and if the person to be selected is not in the list a list item to open a new dialogue to create said person.
My problem is: How can I create the person in the child view model and get it in the parent. I searched (a lot) and found nothing satisfactory.
As far as I know there are at least three possibilities:
1. Use CMs EventAggregator to send messages to the Parent (and everyone else listening)
2. Use a property on the child VM and access this after the WindowManger has closed the Dialogue.
3. Implement IResult
I already did the first one, but this is (as said) not satisfactory. I don't want everyone to get the result, just because he listens to the EventAggregator. The second one is (in my view) not very MVVM like (or is it?), since i cannot control it if it is async.
As far I can tell from CMs doc, the third option is the preferred way. However I found no explanation how to adapt it to my solution.
I have to get user input and this is not possible in the Execute(CoroutineExecutionContext context) method.
Am I overlooking something or is the second method really the best way to achieve this?
2nd method is perfectly ok I have some situations where and I need a response result to proceed and get it upon closure of the view associated with the viewmodel that I call in a different method call, it could be done with a service specifically designed to grab results, if you are looking for S.O.C to avoid conflicts later. The 1st method is actually something I use for a few things, except I directly control what can see the message (new class object to watch for) and the only screens that can react to the message will do something.. 3rd is extremely powerful but I haven't ever actually got into the CoRoutines usage, it was the answer to async before async/await were available. There are lot of IResult examples floating around

Can I save changes to objects to another TR besides those they are locked?

When I try to switch to edit mode for a Report source, a popup comes up telling me
"A new task will be created for the following request of user XXX".
A transport request is also being suggested.
I don't want to save my changes in this request however, but in another existing one. I am not aware of any versioning systems being implemented in my system, and don't know how to check that.
Is what i'm trying to achieve possible? And if so, how?
No, this is not possible. There are very good reasons for this being an exclusive lock -- reasons that you should know about before you attempt to change anything. Briefly speaking
The CTS only notes that an object was touched, not what change was made.
When the transport is released, the entire object in its current state is exported - there is no delta/diff logic involved.
Therefore you can't separately transport changes to the same development object. Furthermore, if you serialize this manually, the second transport will always comprise the changes of the first one.
Things get slightly more complicated with partial objects - you can have LIMU METH objects (methods of a class) in different transports, but as soon as you try to lock the R3TR CLAS main class, you'll have to resolve that.

Creating futures using Apple's GCD

I'm working on a library which implements the actor model on top of Grand Central Dispatch (specifically the C level API libdispatch). Basically a brief overview of my system is as such:
Communication happens between actors using messages
Multicast communication only (one actor to many actors)
Senders and receivers are decoupled from one another using a blackboard where messages are pushed to.
Messages are sent in the default queue asynchronously using dispatch_group_async() once a message gets pushed onto the blackboard.
I'm trying to implement futures in the language right now, so I've created a new type which holds some information:
A group of its own
The value being 'returned'
However, I have a problem since dispatch_block_t is of type void (^)(void) so it doesn't return anything. So my idea of in my future_new() function of setting up another group which can be used to execute a block returning a result, which I can store in my "value" member in my future_t structure, isn't going to work.
The rest of the futures implementation is very clear, except it all depends on being able to get the value into the future back from the actor, acting on the message.
When using the library, it would greatly reduce its usefulness if I had to ask users (and myself) to be aware when futures were going to be used by other parts of the system—It just isn't practical.
I'm wondering if anyone can think of a way around this?
Actually had Mike Ash's implementation pointed out to me, and as soon as I saw his initWithBlock: on MAFuture, I realized what I needed to do. Very much akin to what's done there, so I'll save the long winded response about how I'm doing it.

Resources