Signals and slots have been, since the dawn of Qt, a great way to avoid spaghetti code. You can decouple the elements of the program, and have the inputs from one element and the outputs of another be connected externally with QObject::connect(…).
However, this is not always enough. Many times, when I write Qt applications, I find myself having to define a set of rules between one element’s signal and another element’s slot, based on state and some conditions.
I end up adding an intermediate slot, ‘if’ and ‘switch’ statements, and end up with more spaghetti code. This spaghetti code can arguably be referred to as an “implicit state machine” – a set of rules based on state, that doesn’t look like a designed state machine.
Concurrency
There are two aspects to concurrency. When I cook spaghetti with meatballs, I can put the spaghetti on one burner, and the meatballs on the other burner, and they’ll cook concurrently. That’s equivalent to threading and QtConcurrent. The other aspect is managing my own concurrency. I have to react to the water boiling by adding salt and olive oil, react to the water boiling again by adding the pasta, react to the meatballs being ready by getting them off the stove, and react to the fire started in the kitchen by calling 911. In essence, I cook the spaghetti and meatballs “concurrently” even though I perform one task at a time. That aspect is equivalent to a finite state machine.
Coding spaghetti
The spaghetti header file with C++, Qt, and signals/slots:

If I want to implement my spaghetti boiling mechanism in C++, I would need an intermediate function, something like this:

This if statement is the essence of spaghetti code. I have to route the water-boiling signal through this intermediate function and end up with endless functions and if/switch statements just to implement these implicit state machines.I have to admit that I find myself writing such code pretty often. Debugging and scaling this code is like separating the spaghetti noodles from each other, one at a time (luckily in this example there are only two noodles.)With state machines, I don’t need this intermediate function. Instead, I implement the “raw” signals and slots, and author the rules/logic in SCXML:

Note how I can connect to the same signal twice, and have it perform two completely different actions. And I can do that in a managed and readable way.
Real world examples
If you had it with spaghetti, here are some real world implementations you can do with Qt and SCXML.
Non-modal Dialogs
Modality comes from the imperative nature of languages like C++. It does not exist in nature. Imagine if your car would ask you “Are you Sure?” every time you stepped on the break pedal. When managing states correctly with a state machine, we don’t need modal dialogs. Run the blackjack example, press “Exit” and then “New Game” to see how a smoother UI can be achieved without modality.
Go Back
Many programs have a browser-like “Back” button. This is, however, not always easy to implement. The app has to maintain a stack of states and it needs to be able to restore each of these states. SCXML handles that with the “anchor” module. See the multimedia example for a use of anchors to achieve back-button functionality.
Internet Radio
An internet radio apps receives real-time events from 3 sources: user requests, network responses, and media-engine state changes. Handling the rules of execution and cleanup for such application can become quite complex, and formalizing it in a state-chart makes life a lot easier. This is true for every “reactive” system, a system that receives user and/or system events and has to react to them based on rules.
UI is not just graphics
I upload my music library to my new media-playing device. When I try to play my favorite Pink-Floyd album, I find out that all the songs are duplicated. Slightly irritated, I go to the first duplicated song and choose the “delete” function. After 2 seconds of nothing, I get a modal progress bar indicating that the song is being deleted. After about 20 seconds, I’m back at the menu and can play the song again.So, I had a terrible user experience, and it had nothing to do with flashy graphics. If the states of that applications were managed robustly, and I could continue browsing my song list as the track was being deleted from the disk, I could end up enjoying this device a lot more.
Duplication with the animation-framework states?
People might say this resembles the state XML in the animation framework. The two features do indeed handle “states” but with very different use cases in mind – the animation framework handles GUI states and animated transitions between them, while SCXML is a general purpose “powerhouse” state machine, and can be used without GUI at all. The programming examples above, for example, cannot be achieved easily with the animation states, while animation is harder to achieve with SCXML.
A Project Manager’s Dream
Sometimes projects managers (or other middle-managers) have little or no coding skills. Yet, they want to be able to control and understand the architecture of their product, without taking the coder’s word for it. SCXML provides a clear representation of flow requirements, and since it doesn’t “generate” code, the project manager can look at it and see why the application behaves the way it does, and even make minor changes without the fear of “breaking something”.
More info on the SCXML lab page.
Bon Appetit!
No related posts.
12 comments
Interesting! I’m currently developing a Qt-based application that could benefit quite a bit from state machines. I was considering using the State Machine Compiler (SMC), but now that I see there’s a well-documented, standardized, Qt-based framework, I will certainly give that a try, and see if it fits my need even better.
Please, could you use a food other than spaghetti? Spaghetti in relation to code generally has a very specific idea (something that signals-and-slots were meant to avoid).
Yes, signals and slots are meant to avoid spaghetti-code, and they do so in many ways.
However, the point of this project is that sometimes signals and slots aren’t enough – and you get spaghetti between them, especially when you have a complex set of rules and reactions based on states.
I’ll revise my article to make that a bit clearer
Thanks for the comment
No’am
Remko: Please let me know how it works out!
This is the best time to affect a feature as it’s being created.
Yes, projects managers usually have little or no coding skills, but they don’t like to be reminded!
Any plans for offering a graphical editor? Moving to XML will save managers to code in an imperative language but just to do it in a declarative one. Probably they (and my current users) will appreciate a way to describe at least a subset using an editor.
Thanks.
Das, a graphical editor would be a natural addition to a future version, and having a declarative language that maps pretty closely to UML would set the ground for that.
However, writing that editor is not trivial, and we want the functional elements to be in place and working before we get into the tool work.
We also expect 3rd party SCXML graphical editors to appear in the future, and plugging-into them might be a good solution.
So to your question, it’s definitely planned but not committed upon until we see how people react to the current offering
Don’t give project managers XML! To them it looks just like code, and they’ll start thinking of themselves as coders. Before you know it they’ll start micromanaging your coding. Better to give them a diagram. And a box of crayons to color it with.
This sounds very promising!
I’ve been looking into SCXML for a while now, especially in the context of multimodal user interfaces (GUI+VUI) in in-vehicle infotainment.
We’re currently using a propietary statechart-based HMI-developement tool. Even though I don’t care much about graphical editors they are absolutely necessary because our UI-designers would never touch any XML “code”. I personally really like Qt, I have been working on desktop applications as well as applications for devices (Openmoko). With the possibility to design UI-flow with a graphical statechart-editor, creating UI-layout with Qt Designer, text and translation with Qt Linguist and leaving the rest to coders, Qt would make a great framework for our needs.
One more thing, could you please post a link to the repository? I couldn’t find the project neither on the svn (does it still exist?) nor on the git repo.
Thx a lot!
Nikolaus: The link is svn://labs.trolltech.com/svn/xml/scxml
It’s published at the lab page (http://labs.trolltech.com/page/Projects/xml/scxml) which is linked from this page.
Re. project managers & designers: if this project gains momentum maybe in the future we’ll be able to supply a graphical tool to go with it, thus enabling interaction designers and non-technical managers to understand the charts.
Until then, hopefully this XML can provide at least some help in the term of formalizing and organizing those state machines.
It sounds handy, but my attempt to test it failed (OS X, Qt 4.4.3). I’ve checked out the latest version and ran qmake & make.
I got “error: ‘QStateMachine’ has not been declared” all over the place and out of it several other errors. It occurs on building the qtscxml.o.
Any hints what is wrong?
Thx!
Florian, thank you for the bug report and for your assistance in fixing it.
The fix has been submitted and should soon be available on the SVN.
Please let me know if you have more issues or if you have comments about the solution itself.
Regards,
No’am
Comments on this entry are closed.