News for hackers. Stuff that matters.
Re:Scala Best Practices by century19 on Friday October 31, 2014 @08:06AM (#8538310)
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 } } }

Re:Scala Best Practices by wernerb on Friday October 31, 2014 @08:22AM (#8538342)
Actors 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.

Re:Scala Best Practices by bad_user on Friday October 31, 2014 @08:41AM (#8538406)
I'll add a better example, thanks for the feedback.
Re:Scala Best Practices by bad_user on Friday October 31, 2014 @09:11AM (#8538526)
As @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

Re:Scala Best Practices by century19 on Friday October 31, 2014 @09:26AM (#8538592)
OK, I think I get it. Will have to try out the example.

Thanks for the explanation and the code.