3 ms·
Hi bad_user, I seen this on Twitter and just by scanning it quickly I learned some things, so that's why I posted it here and thanks for sharing. Can I ask ab
by century19 12y ago
Hi bad_user,
I seen this on Twitter and just by scanning it quickly I learned some things, so that's why I posted it here and thanks for sharing.
Can I ask about rule 5.2. SHOULD mutate state in actors only with "context.become"?
How would you use become to avoid using vars to keep state in an Actor like this?
class Account(var account: AccountDetails) extends Actor {
def receive = {
case msg: UpdateAccount => {
account = msg.account
}
}
}
- wernerb 12y agoActors are good at encapsulating state, therefore using mutable variales inside an actor through is very natural, and one might even question if an actor is needed if it does not have any mutable state inside it. However, 5.2 does not concern the elimination of vars, but rather better management of multiple states (Finite state machines) Your example, just like the example in 5.2, only has a single state, so no context.become is strictly necessary. The author makes clear that when you have multiple states, the collection of top-level mutable vars will be hard to maintain. I had this problem a few times and I am glad this gets mentioned in the guide. I agree though, that a better example would include at least two states.
- bad_user 12y agoI'll add a better example, thanks for the feedback.
- bad_user 12y agoAs @wernerb already pointed out, the idea is to use context.become such that inside your actor the only side-effects happening are due to context.become, otherwise the data structures are left immutable, the helper functions are left pure, etc... and it becomes easier (less error prone) to manage complex actors that way. Another side-effect of this for example is that you're not going to worry about vars that leak into Future computations, which is a mistake that even experienced developers are doing, because it's an easy one to make. Here's your sample translated into a state-machine with 2 states: https://gist.github.com/alexandru/63eebe8e49e796f31e73 https://gist.github.com/alexandru/63eebe8e49e796f31e73
- century19 12y agoOK, I think I get it. Will have to try out the example. Thanks for the explanation and the code.