FSM vs become/unbecome in Akka - akka

Akka provides two somewhat overlapping ways to manage actor states, Finite State Machines and unbecome/become. What are their respective benefits/drawbacks? When should one of them be chosen over the other?

FSM is a DSL that allows you to build more sophisticated, readable state machines than would be possible using the core actor API. You could potentially show the FSM code to a business person and they could validate the business rules.
The FSM DSL allows you to compose things together more cleanly. For example transitions allow you to factor out logic that would have to be duplicated across actor become behaviors. Also you can subscribe other actors to be notified of transitions which helps with decoupling and testing.
Also timers are integrated nicely into the DSL and things like cancellation are handled cleanly. Coding timeout messages using the scheduler has a number of gotchas.
The down side to FSM is that it's a DSL and a new syntax for other team members to digest. The up side is that it's a DSL and a much higher level abstraction. I think agilesteel's threshold of 2 states is a good one. But once you get past 2 states the benefits of FSM are really compelling.
Definitely read the FSM docs and the accompanying examples contrasting become and FSM.
One note re: "popping" a behavior using unbecome - the default behavior is to not use the behavior stacking. It is only relevant in a small number of use cases (ie, usually not state machines).

Become/Unbecome are very lightweight in contrast to FSMs. So unless you have more than 2 states (on/off for example) and/or complex state change policies I wouldn't convert Become/Unbecome to a full blown FSM. Other then that, I think there are only minor differences...Like for example FSMs give you a nice built in timer DSL:
setTimer("TimerName", msg, 5 seconds, repeat = true)
// ...
cancelTimer("TimerName")
Or for instance I'm not sure if it's possible in an FSM to "go back" to the previous state, there is only "go forward", since you have to explicitly specify which state to go to. Whereas unbecome gives you exactly that.

Related

State design pattern usage in embedded software

I have been solving following problem. I'm a newbie in C++ and I need to implement
a state machine for an embedded software. This state machine should constitute
core of an application logic. It should control transitions between states
"STANDSTILL", "RUN" and "FAULT" of a controller. These transitions occur based
on: logic inputs state, analog inputs state, messages received over communication lines and messages created internally in the controller's software.
I would like to implement this state machine in such a manner that I utilize the
power of the C++ (object oriented programming). So I have spent some time in
looking for some appropriate design pattern. I have found the "state" desing
pattern but I am not sure whether it is a good choice for me. As far as
I understand the definition in right manner it is intended for situations when I
have some object (so called context object) which behavior (methods of its public interface) is strongly dependent on its state.
My first idea was that the so called context object could be the controller itself. (I mean a class which will realize the software model of the whole device.) The state dependent methods could be the methods asociated with the above mentioned inputs processed by the state machine i.e. logic inputs, analog inputs, messages received over communication lines and internal messages. But I am not sure whether it is good approach. Does anybody have any experience with such usage of the state design pattern? Thanks for any suggestions.
Just because you are using C++, you are not necessarily using object-oriented design. Nor do you have to use OOD when implementing trivial things. It is quite feasible to implement a state machine without involving OOD, since it is such a simple data structure. Basically it is just an array (of function pointers) with named members.
The "pattern" is known as finite state machine. A typical C implementation for embedded systems can be found here. You could write a simple class around that array. State machines in embedded systems are almost always static and read-only, so the class would have to be a "Singleton". You'll find that there's no obvious benefit of using a class here.
the state pattern is a good design to start with. But as mentioned, there are existing tools that can generate the code for you. Another one you could look at is http://scxmlcc.org. This one create code that uses 'the power of C++' and is also based on the state pattern design.

Finite State Machine vs ID3 Decision Tree

I have a project that is running on an Arduino like microcontroller and it is currently a soup of mixed IF ELSE statements that can be hard to follow as all the different "rules" are applied and moving through the states. I essentially have (6) modes/states that have been wrapped into functions that are managed via a Case stement in the main loop and the changes needed for transitions are buried at the top of those functions to allow for nearly any state to transition to another state. A little research has led me to Finite State Machines (FSMs) but I also see a lot of people pointing to ID3 and similar decision trees. The inputs that determine state are well defined/known. Given my system isn't trying to solve for "known unknows" would the effort of a decision tree vs a FSM be worth it?
If you use ID3, it will go through the same process for every new "input" in order to produce the output/state, where in an FSM you move from state to state in a single step.
So, In your case it really seems that using ID3 adds unnecessary compelxity. I would opt for FSM.

What is the point of Boost::Signals?

Firstly, I am an absolute beginner in programming, so don't make fun of me too much.
The only thing that I have seen signals used for are GUI toolkits, and GUI toolkits all come with their own signaling. So, can Boost:Signals even be used with these GUI toolkits? Would this be a good idea? What other applications do signals have?
Signals is an event messaging implementation, much like Smalltalk/Objective C Messages or Events in various other (e.g. C#) lanugages.
You can use them for a wide variety of tasks, take a look at the Observer Pattern
Why would you use the Observer Pattern?
The benefits are largely organisational, when you work with large applications it's is important to apply patterns of reuse that help maintain development team coherence.
When the implementation of a particular pattern becomes de facto (or close to) it's especially useful because it means that lead up times for new team members are likely to be expedited, not only if they have used the implementation before, but also because the popularity of the implementation will mean that there are widespread resources, and documentation available to speed learning.
From a pure code perspective, ALL patterns appear as bloat, but when you begin to understand that upwards of 60% of the costs involved in software development are in maintenance life-cycle, it is well worth the additional code to gain coherence.
The other benefit is to aid in software reuse, depending on the style of implementation, the Observer Pattern can assist in modularising and decoupling classes from one another. I would suggest that this is also an organisational benefit, in as much that different teams can build components more easily, or simply because components are easier to replace.
Just my two cents, signals are not only used in (or for) GUI toolkits. They are used in contexts where you want to decouple the producer of a datum with the receiver of it (the observer pattern mentioned above, for example). If you mix that idea with threads, you can implement actors easily, an interesting pattern for concurrent tasks (Erlang and Scala use actors, for instance).
One possible use would be in the implementation of a GUI toolkit. You'd basically set up the wiring to get messages (or whatever they happen to be called) from the native system to produce signals. From there, the code for routing and handling signals can be (at least somewhat) portable.
In addition to the Observer pattern that others have mentioned, anytime you find yourself having to write a callback function, so that one class can notify another that something has happened, then you can use Signals and Slots instead. The great advantage over callbacks is that it takes care of lots of the boiler plate code to add and remove the callback function, and deals with automatically disconnecting when either the caller or the callee go out of scope.
Callbacks are really just an instance of the Observer pattern though.

Monads and Actors

I've been trying to find anything that discusses when you should favor the use of monads over actors (in concurrency scenarios), but I've found nothing. In particular, I'm wondering about the use of the Reactive Extensions (LINQ to Events) vs. F#'s MailboxProcessor. Please give examples in addition to any philosophical reasoning you might have.
Update
For better context, the Reactive Extensions implement the continuation monad in the form of IObservable/IObserver. I'm not necessarily saying I have to use F#, just that F# has a concrete "actor model" available in a .NET language in the form of MailboxProcessor<'T>.
What I'm trying to understand is when to use a monad (in this case a continuation monad) vs. an actor model for concurrency purposes. Where the monad (as I understand it) doesn't introduce state, the actor has its own internal state that is modified as necessary to provide protected access.
I've seen a number of examples of using both: Rx and node.js (CPS, not really the continuation monad) vs. F#'s MailboxProcessor and Scala's Akka framework. I just don't know why you would choose one over the other.
I'm not sure that the question makes sense as phrased - there are many different monads (e.g. the identity monad, the list monad, the option monad, ...), most of which have nothing to do with concurrency. Furthermore, it would be helpful to know more about the particular scenario that you're dealing with - "concurrency" is a bit of a nebulous topic. Depending on what you're trying to achieve, F#'s async workflows (which are built on the Async monad) might be your best bet.
If you're using F#, I'd recommend against using LINQ-to-anything directly, since those libraries have a very alien feel when accessed via F#. You could, however, create pleasant F# wrappers (such as the existing Seq and Observable modules). Additionally, for monadic types, you could create a computation expression builder (e.g. you could create a builder using the Reactive Extensions which would enable you to use computation expressions to build and compose IObservables).
Please excuse my newbie-ness as I'm just learning F#.
I'm intrigued to see the use of RX in place of a MailboxProcessor, if you have any links to relevant materials.
With my limited understanding; I would choose MbP's in my own code as events are a bit messy to set up in F# (from what I can take from this article: MSDN). And you need events for RX to hook into right?
Where as with a MbP all I need is a discriminated union of messages, a list of functions I wish to be executed when a given message is received. And the mail box processor that handles this.
This all looks pretty neat in the code. I can bunch my MbP's together in a module then my "object" module looks like
Record
Message DU
Wrapper with some getters and setters that post data to the MbP
For me this looks a lot neater than it would If I wrote my code with events as described in that MSDN article I linked to.
Though I am just an F# junior so I may be a miles off with my reckoning and it is a look-&-feel thing rather than a suitability-for-purpose choice (as I'm not qualified to make that call, yet)
Would you accept answers from the Scala world?
If you seek "a purely functional alternative to actor model" then please see this great post from Paul Chiusano's blog
pchiusano.blogspot.ro/2010/01/actors-are-not-good-concurrency-model.html
(archived here: http://archive.is/NxNLc)
and some references below:
http://noelwelsh.com/programming/2013/03/04/why-i-dont-like-akka-actors/
Actors do not Compose
Akka’s Actors are not Usefully Typed
The type system is the reason we use Scala.
https://opencredo.com/akka-typed/
Unfortunately, the current API suffers from a few drawbacks, which are to a good degree associated with the lack of type safety
http://doc.akka.io/docs/akka/snapshot/scala/typed.html
Status of this Project and Relation to Akka Actors
Akka Typed is the result of many years of research and previous attempts (including Typed Channels in the 2.2.x series) and it is on its way to stabilization, but maturing such a profound change to the core concept of Akka will take a long time
A side-effect of this is that behaviors can now be tested in isolation without having to be packaged into an Actor, tests can run fully synchronously without having to worry about timeouts and spurious failures. Another side-effect is that behaviors can nicely be composed and decorated
Composable application architecture with reasonably priced monads
https://youtu.be/M258zVn4m2M?t=1955
https://youtu.be/M258zVn4m2M?t=1986
The concept of "function passing style" from Heather Miller might be key to a distributed functional programming model.
SF Scala: Heather Miller, Function-Passing Style, A New Model for Distributed Programming
Update 12/2018 : now we can use Aecor which provide the means to:
implement business domain logic with a functional programming model and
use an Akka based runtime
"behaviors belong to the domain layer and runtime is out there in the infrastructure layer."
Source: https://pavkin.ru/aecor-part-3/, http://aecor.io
I'm going to respond to my own question and say you should use both. This is based on Don Syme's post. A MbP uses the Async computation to do its work, and the Async is a thread-aware continuation monad. Looks like you can use it by itself for some uses, but the MbP definitely requires it.
I don't really like this answer, and I'd be happy for someone to respond with a better explanation of when to use each.
Updated:
See MiniRx, which is now apart of FSharpx, for an implementation of an Rx-style monad implemented using MailboxProcessor. As MailboxProcessor is itself implemented using the async monad, these pieced to indeed work together. They are just different means of abstraction.

What Design Pattern to use?

The problem to model is this:
A hierarchy of levels within an Army, starting with the national army in whole, through field armies, subunits, and eventually the individual men. Each level may involve links to one or more other classes such as General or Officer or whatever. The units within say a field army need to be able to communicate with each other, especially for purposes of modeling morale, cohesion, etc, as well as with those of any enemy field army (e.g. a unit routing in my army affects the enemy morale positively). Furthermore, each unit needs to communicate with those above and below it in the hierarchy (for obvious purposes).
I was thinking of having the links in the physical hierarchy represented by actual pointers (possibly bilateral) in each of these entities' classes (e.g. army* in each unit and unit* or a whole collection of them in each army) and then making use of the observer design pattern to implement any communication in other cases (such as the case I mentioned above).
However, being no expert in design patterns or programming for that matter I do not know whether there is any other more efficient manner to do this. Any help would be greatly appreciated.
There is a model/design pattern for communicating events between disparate entities that may not know of eachothers existence before the communication happens. The pattern is called 'Publish/Subscribe'.
Each entity sends events it wants to publish to a broker and tells the broker about what kinds of events it would be interested in. The broker handles making sure the subscribing entities learn of events they find interesting that are published.
This is like the Observer pattern, but in the Observer pattern each interested entity subscribes individually to each entity it wants events from. I think this could result in a lot of overhead because that requires everybody to care about creation and destruction of things.
Anyway, there is a nice Wikipedia article on Publish/Subscribe.
I would use the Composite pattern (which basically means a tree of some form) for the individual armies. And possibly Observer for relationships up and down the hierarchy or with siblings. But Observer requires too much registering and unregistering for it to be workable in the general case.
Sounds like "Small Boy With A Pattern" syndrome. You're looking for a pattern instead of thinking about your problem.
The natural data structure for a hierarchy is a tree. I'd start with that.
If the requirement is that every unit in the tree must communicate with all others, I'd say that Observer is not for you. Every unit would have to be register with all the others. You'll have an N-squared firestorm of messages every time an event was fired.
Mediator might be better. Units would send events to the mediator, allowing consumers to register their interest in receiving a particular kind of message. Producers and consumers only know about the mediator, not each other. Loose coupling is your friend.
For modeling the structure, this looks like classic application of the Composite pattern. Then you can use Visitor or Interpreter for modeling the operations on sub-units.