3 ms·
Create a "box" type, say AccountAction, that represents something that has to happen atomically. The AccountAction-ness ripples up the chain, so user functions
by lmm 12y ago
Create a "box" type, say AccountAction, that represents something that has to happen atomically. The AccountAction-ness ripples up the chain, so user functions may return AccountActions, or may call several AccountActions and return a single combined AccountAction for things like this Transfer. At the top level there can be a single "actor" that's responsible for processing accounts that processes AccountActions one at a time; user code passes an AccountAction[T] and gets back the "unboxed" T, the actor having performed the action atomically.
Ensure that the only way to construct something that accesses a BankAccount is as an AccountAction. You're automatically assured that any code calls the "actor" eventually, because there's no way to e.g. print an AccountAction[String] to standard output - sooner or later you have to make the call. User code can still have races if it tries (e.g. if it deliberately calls the "actor" separately for the withdraw and the deposit), but such code is much more obviously wrong from reading and looking at the types (particularly if you call your actor call something like "unsafeTransaction"). If you've got a single consistent point of entry/exit (e.g. this is a message-processing system), you can put the actor call there.
The only hard part is making this easy enough to use that it doesn't overcomplicate the code. Provide easy syntax for composing two AccountActions - something that's as clear and simple as just calling two methods, but with just enough difference to make it clear from the code whether you're using one or not - e.g. non-action calls use "=", action calls use "<-". Make a library of functions for doing things like "perform a list of AccountActions as a single, atomic AccountAction". Better yet, make AccountAction conform to some interface such that that library already exists.
(Of course by now you've probably guessed that AccountAction is just an alias for the reader monad. But the naming is valuable; it keeps everything more concrete and clear)