The Design of Software (CLOSED)

A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.

The "Design of Software" discussion group has been merged with the main Joel on Software discussion group.

The archives will remain online indefinitely.

State Machines

I've been doing code reviews recently, and have noticed that although the general quality of the code has been pretty good, one place where things are really muddled is in the user interface code.  The way that the user interface state is being maintained and controlled is a real mess.

One thing that I thought might help with this would be to get folks to model the user interface as a hierarchical state machine or statechart.

Can anyone recommend a visual tool to allow such a design, preferably with the ability to spit out .NET code implementing the machine?  Doesn't need to be free.  Thanks in advance
GUI Bill Send private email
Monday, January 16, 2006
I do not know what is a "hierarchical state machine". But have a look at MS User Interface Process Applicaton Block (UIPAB).
Monday, January 16, 2006
Most programmers don't like state machines because it requires thinking. Using the fight-or-flight instincs of just putting in another variable are more familiar.
son of parnas
Monday, January 16, 2006
That's my impression as well.  Thanks for the validation.
GUI Bill Send private email
Monday, January 16, 2006
Short answer: I don't know of any such software.

That said, I haven't seen anything that suggests a hierarchical state machine would be a practical way of modelling user interfaces to this extent. The sheer complexity involved and the number of permutations possible would quickly escalate the cost of developing a state diagram to the point where it would be more expensive than traditional debugging and refactoring tactics.

By way of example, consider modelling all of the possible interactions in a word processor.

I would love to be wrong.  Can anyone point to a theoretical white paper that demonstrates modelling a non-modal user interface in this fashion?
Anonymous Coward
Monday, January 16, 2006
> Can anyone point to a theoretical white paper
> that demonstrates modelling a non-modal user
> interface in this fashion?

If it's a theoretical white paper it doesn't really have to exist, does it?

It's ironic though that the solution to dealing with complexity isn't actually to deal with complexity straight up, it's to hide it behind layers of software even an archeologist wouldn't want to peel back.
son of parnas
Monday, January 16, 2006
My guess based on you vague explanation of the problem:

Is this for Windows dialog boxes?

Is this for stuff like
- If this radio button is checked show that option
- If this check button is checked that other options is greyed
- If this combo is set to option B, then fields C+D show, but otherwise E+F show, etc.

Many programmers, and most Windows programming books cock this up, by trying to suggest putting this type of logic in each button's/control's event handler (and hence you get bugs where if the user clicks the options in a difference sequence the wrong other controls are greyed/ungreyed, etc.)
S. Tanna
Monday, January 16, 2006
We use the "Objects as States" design pattern to create finite state machines for business workflow types of applications. However, this is complete overkill for a standard CRUD app. What type of application is this? Standard CRUD apps can usually get by with a couple of state variables to handle things like the current mode (edit, view, etc.) and the state of the data currently being worked on (new, existing, deleted, etc.). Business workflow apps should consider using a dedicated FSM.

If you have a lot of state handling mixed into your GUI then you may benefit the most by simply trying to refactor the code into something that is closer to a pure Model View Controller pattern (MVC). 

As far as tools are concerned, you will probably find that there are a lot of really high end solutions (business workflow management) but not much at the lower end. The simpler the state machine becomes the less you need a tool to help manage it. It all comes back to the type of appliation that you are trying to build/maintain.
Turtle Rustler
Monday, January 16, 2006
I haven't used it yet and it works on text files rather than diagrams, but you might be interested in:

State Machine Compiler
Chris Winters Send private email
Monday, January 16, 2006
I was thinking of something along the lines of the Statemate approach described by David Carel in several places, for example here: or in his book, "Modeling Reactive Systems with Statecharts"

Admittedly, describing something like a word processor as a state machine would be very (very very) complex, but the software must have some way to provide the same functionality already, if it works correctly. Whatever mechanism they are using, someone had to design.  If you have to spend the time anyhow, it seems like it would be a better solution to at least try to use a method that is well understood, rather than the "instinctive" approach described in an earlier posting.

Anyhow, the kinds of software that these folks are writing is not at the same level of complexity as a full featured word processing application.  These are modules for a web based content management system, so there are screens to do the normal CRUD stuff, screens to connect different elements to each other, and stuff like that. 

Since one of the biggest problems I noted while doing the reviews was with how things were being enabled/disabled, made visible/invisible, colored red or blue, etc, even capturing this kind of logic in a state machine would be a step in the right direction, or so it would seem.

I'd like to at least try it, but without a tool of some sort, I know it'll never fly.
GUI Bill Send private email
Monday, January 16, 2006
"Many programmers, and most Windows programming books cock this up, by trying to suggest putting this type of logic in each button's/control's event handler "

This is precisely what is going on.

Instead of pushing the various properties onto the control, I'd like to have the control pull the properties (using databinding, I guess) from state being managed in a state machine.
GUI Bill Send private email
Monday, January 16, 2006
For SDK and MFC programs, IMHO the best simple way to do it (which I realize is getting like a state machine - but you don't need to get bogged down in an deep academic discussion - I prefer to think of it as a "pattern" or rule for coding dialogs well) is write *one* function per dialog which handles *all* the greying/enabling/hiding/showing of controls.

This function, is called whenever the state of one of the controls (which affects the other controls) changes

This function is also called when the dialog box first appears (at the end of WM_INITDIALOG) when you've put the controls up with their initial content.

(BTW it also helps to also have a helper function (for the whole app), which does ShowWindow/Enable on a true parameter, and Hide/Disable on a false parameter).  Let's called it ShowEnableWindow  for the sake of argument).

And what does this function contain?

Simply a series of calls to EnableWindow or ShowEnableWindow for each control [whose state can changed to grey or hidden] on the dialog.  Only one call per control.

One code path for all enabling/disabling:

This avoids the order of controls problem I referred to earlier.

It also avoids a variant of that - the initial state of controls not being set right on certain data initially in the dialog (another common problem of this) type.

And allowing one call to ShowWindow/EnableWindow per control in that function:

This avoids another fairly common problem which is flickering of dialog controls between multiple states (e.g. in lots of apps, you click a radio button, and some other control briefly flickers disabled for no good reason)
S. Tanna
Monday, January 16, 2006
BTW delegating this type of enabling/disabling to the controls themselves (as suggested in your comment) is IMHO a massive mistake

Which controls are enabled/disabled is NOT a property of the controls themselves

Which controls are enabled/disabled is a consequence of the overall content of the dialog box, and is best thought of that way.
S. Tanna
Monday, January 16, 2006
In my most complex app (ED for Windows) I developed a system for handling all UI based on sets of rules. Each dialog box has a rule table which describes the interactions between controls, how they are populated, when they are enable/disabled/hidden etc. This rule table is data, not code. Code iterates the table to evaluate the rules as required.

In a typical Windows app you write new code for every dialog, repeating much of the same effort over and over. In my implementation there is only one set of dialog box code for the entire app.

If I need some new functionality, I add this as a new capbility to the rule system. This has proved itself over and over during the development of ED. It has saved considerable time and delivered a better product. That said it is in itself a complex beast.
Neville Franks Send private email
Monday, January 16, 2006
I spent some time searching for such a tool and did not come up with anything that I liked. Take a look at is the web-site of a guy who wrote a interesting book regarding the use of statecharts and he provides a C/C++ based framework for the same.
Monday, January 16, 2006
I used something similar to what S. Tanna mentioned.

The UI has a finite # of states (Answered, Awaiting Answer, AcceptingAnswer, etc.).

When someone clicks or types, the control calls the procedure that decides what the current state is and what the next state will be. Based on that, it either ALLOWS the user action to just be processed normally or responds to the user action.

Example: if user presses <enter> and we're in the "ExcerciseFinished" state, then we just go to the next excercise.  If they're typing an answer, <state=AcceptingAnswer> then we just let the text box respond normally.
Mr. Analogy {uISV} Send private email
Monday, January 16, 2006
S. Tanna:

That's a good idea to put all of the property setting into a single method called at a well defined point in the lifetime/main processing loop of the GUI.  That provides a push alternative to the pull idea I was describing above.  Since I don't know how well databinding works in general, it's probably a superior solution to the one I was kicking around.

"Which controls are enabled/disabled is a consequence of the overall content of the dialog box, and is best thought of that way."

Perhaps I misrepresented what I was trying to do.  I'm talking about implementing a state machine at the dialog box (or web page in this case) level to manage all of the state.  At some well-defined point in the processing loop (probably just before painting), I would send a signal to each control, instructing the control to query the state machine.  Based on the results of the query, the control would know how to render itself during the subsequent paint operation.

The controls wouldn't be managing any of their own enabled/disabled state, just asking what it is so that they can draw themselves correctly.
GUI Bill Send private email
Monday, January 16, 2006
Hi Neville,

That's a pretty cool idea.  I tried something similar in Java once, using the JESS rule engine to interpret everything.  It didn't work out too well, though, because of the bizarre JESS syntax for writing rules.  Thinking about it, though, I doubt a full-blown production system would be necessary.  Maybe I could roll something quickly by hand along the lines you mentioned in your post.  thanks
GUI Bill Send private email
Monday, January 16, 2006
Thanks Chris Winters and Grok2, I will have a look at the links you provided.
GUI Bill Send private email
Monday, January 16, 2006
> It didn't work out too well, though, because of the
> bizarre JESS syntax for writing rules.

The problems with rules once they get complex is ordering. In a UI order is important. Rules don't naturally follow the best order for a problem. That's why in prolog you are often stuck with enforcing order through hacks like cut.
son of parnas
Monday, January 16, 2006
> The controls wouldn't be managing any of their own enabled/disabled state, just asking what it is so that they can draw themselves correctly.

If they're Windows Controls, Windows already does this - you need to exploit the mechanism that's already there and BTW you need to differentiate two things -- or else you will end up in a horrid mess.

1. The bit that handles drawing of the controls based on their state (enabled/disabled/etc)

What determines this should be the standard Windows flags, set by (for example) EnableWindow, ShowWindow.

For built-in standard Windows controls, Windows handles this for you

For your own custom-controls and ownerdraw controls you need to pick up on these flags (for example, using the bit flags in DRAWITEMSTRUCT)

2. The bit that handles setting the state of controls, for example using EnableWindow, etc. This is part of the app, usually the dialog containing the controls, rather than the control itself.

What you want to avoid in your solution, is duplicating the functionality of Windows internal flags behind EnableWindow, ShowWindow, etc.
S. Tanna
Monday, January 16, 2006
If you want to read "The STATEMATE semantics of statecharts" (referenced above) without paying the ACM for a copy, try this ...
Developer #13
Monday, January 16, 2006
how about just using a pencil and paper to sketch out your fsm and then come up with a state transition table, etc.?

Monday, January 16, 2006
I could do that, but the people's whose code I am reviewing wouldn't go for it.  It's much "easier" for them to "design while typing"  That's the main reason I'm looking for a tool - I need to make it "painless" to have any chance at "buy-in"
GUI Bill Send private email
Monday, January 16, 2006
Just wondering...

I did word processor application by myself (
and have some doubts about "a word processor as a state machine would be very (very very) complex".

I don't think it is that complex.

Any word processor as an application consists of set of
micro/mini state machines - there is no single FSA there. From document parser (e.g. html parser - pure state machine) up to UI code itself. Generally speaking any GUI application is a state machine by definition - single GUI thread and single DispatchMessage.

Problem of GUI code is in its nature.
Very frequently its design (coding) happens at the same time as design of specification. This is what I call  Design Time WYSIWYG. And yes, sometimes it follows to deterministic chaos. The same apply to formal state machine - when it is complex it is non-maintainable too.
Decomposition on simpler procedures(machines) with  reducing number of allowed states is the only fesaible design practice. Still it is more art than science.

I've seen a lot of attempts to formalize the process - nothing even close to ideal. Probably it makes sense to take a look on XForms
( )
as an attempt to formalize this. But something tells me that this will end up with something similar to XSLT - simple in principle but too complex in practical applications.

IMHO of course.
Andrew Fedoniouk
Tuesday, January 17, 2006
Personally, I think all this talk about state machines is a bit of a red herring.

Take a step back...The original problem was spaghetti UI code.  How to address this?

I personally find Fowler's "Rich domain model" pattern really helpful. 

First, I'll create an object that encapsulates both the data and the business rules for a customer, invoice, etc.  When methods are invoked on the domain object, the object will fire PropertyChangeEvents to signal that the state of the object has changed.

Then, I'll write my UI code.  UI widgets will have event handlers that will invoke methods on the domain model, and the UI code will also have listeners that update the UI in response to different events.

If you code this way, its impossible for the UI to get out of sync with the underlying object that you're manipulating.
Tuesday, January 17, 2006
I should also add that this is also really a matter of good design habits.  You aren't going to find a tool that can "painlessly" transform poorly organized code.
Tuesday, January 17, 2006
Hi guys,

If I understand properly what are you talking about, then

could be interesting for you. Maybe.
Tuesday, January 17, 2006
Hi Dave,

I'm not sure the solution you offer lines up well with the problem I was trying to describe.  It's not that the UI is getting out of synch with the domain model (though I will admit there were a couple places where that was screwed up too - since corrected).

The main problem is with the state of the application, not the state of the business.  What controls are active, which are using special formatting, that kind of thing.  Right now the approach is ad-hoc - the programmers are setting those values all over the place according to no rhyme or reason that I can detect.

I would prefer a more methodical approach to maintaining the application state according to application rules, similar to the way you maintain business state according to business rules.  A state machine seems to offer that kind of rigor (among several other clever solutions offered by previous posters, thanks!)

The end result I seek is similar to what you describe in that I want the GUI elements to observe a model of the application in order to determine their visual properties, but it's really not a business/domain layer issue I am trying to solve at this point - it's all in the application layer.

Sorry if I wasn't clearer, and thanks for the input.
GUI Bill Send private email
Tuesday, January 17, 2006
You might want to use events for this so that you don't have to worry about keeping track of the state of so many things.

Tuesday, January 17, 2006
If it is a business app the fsm is usually restricted to
a line of states from 'started' to 'finished' with one extra 'fail' shown below the sequance.

Each state from 'started' to before has a link to 'fail'.

If 'on hold' is permitted this can be put above the line with a double headed arrow between the state and 'on hold' with a note saying that record of the previous state is required.

so it goes - John
John Griffiths Send private email
Wednesday, January 18, 2006
I don't know of any tool, but _Constructing the User Interface with Statecharts_ by Ian Horrocks is a great book that you might want to check out.
Saturday, January 21, 2006
I might be misunderstanding this thread, and I'm not sure whether the OP is using Delphi, but there is a concept in Delphi called ActionLists. I use Delphi and I find that this one component is a godsend for state management in any type of form including (in our case rudimentary) rich text editors.

Basically, though, you drop this component on a form, create all the actions for the form/dialog, and all the UI elements (menus, popups, controls, etc) connect to the relevant actions in the list.

From that point onwards, you can forget about the UI and all states can be defined from within one event of this control. In addition, more than one control can share an action (i.e. main menu item and popup item) and changing the state of one action may have an effect on multiple controls.

Not sure if this counts, but it works very well for us.
Ewan McNab Send private email
Sunday, January 22, 2006
I found a lot of newbies and even experienced our inhouse C++ programmers really fall down when it comes down to UI states.

For instance we have a very complex dialog in which the user can do many actions (drag/drop, double-click/single click, right click & send, various keyboard accelerators etc) to a range of source object types and target destinations. Some of these actions also enter/exit modes which constrain subsequent actions.

Its obvious to me that when broken down into a state diagram,  the complexity is much more managable, yet programmer after programmer working in the area all seem to make ad-hoc patches to the code rather than thinking of the global state.   

I have done state-diagrams, but would also love a compiler to turn it into design patterns.
Grant Send private email
Thursday, February 09, 2006

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
Powered by FogBugz