<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Rui Figueira's Blog &#187; State Diagrams</title>
	<atom:link href="http://www.crazygaze.com/blog/tag/state-diagrams/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.crazygaze.com/blog</link>
	<description>Knowing is not enough; we must apply. Willing is not enough; we must do.</description>
	<lastBuildDate>Fri, 24 Sep 2010 16:22:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<item>
		<title>Simplifying code using states</title>
		<link>http://www.crazygaze.com/blog/2007/12/19/simplifying-code-using-states/</link>
		<comments>http://www.crazygaze.com/blog/2007/12/19/simplifying-code-using-states/#comments</comments>
		<pubDate>Wed, 19 Dec 2007 16:46:23 +0000</pubDate>
		<dc:creator>ruifig</dc:creator>
				<category><![CDATA[Game Development]]></category>
		<category><![CDATA[code design]]></category>
		<category><![CDATA[State Diagrams]]></category>
		<category><![CDATA[UML]]></category>

		<guid isPermaLink="false">http://www.crazygaze.com/blog/archives/39</guid>
		<description><![CDATA[Lately I have been refactoring czPlayer to add more features and make future maintenance easier. Some parts of the code are almost 10 years old, when I first started playing with sound coding. Needless to say, my code style and quality has improved a lot in 10 years, and it&#8217;s a funny thing to look [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I have been refactoring <a href="http://www.crazygaze.com/blog/czplayer">czPlayer</a> to add more features and make future maintenance easier.<br />
Some parts of the code are almost 10 years old, when I first started playing with sound coding.<br />
Needless to say, my code style and quality has improved a lot in 10 years, and it&#8217;s a funny thing to look at code this old. <img src='http://www.crazygaze.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
As I was refactoring the code, I found a lot of ambiguities and redundancies caused by member variables added over time.<br />
Let me explain&#8230;.<br />
I had a class responsible for MOD processing, and some of the member variables were:</p>
<pre class="brush: cpp;">
class MODModule
{
	// ...
	bool m_loaded;
	bool m_playing;
	bool m_paused;
	bool m_reachedEnd;
};
</pre>
<p>What&#8217;s the problem with this approach ?<br />
Let&#8217;s see&#8230;<br />
Suppose I want to call methods on the MOD object (e.g: Pause(), Resume(), etc)<br />
I need to make some checks in each method.</p>
<p>To pause&#8230;</p>
<pre class="brush: cpp;">
if (!m_loaded || m_playing || m_paused)
	return SOME_ERROR;
m_pause = true;
// ... do pause stuff
</pre>
<p>Then to resume&#8230;</p>
<pre class="brush: cpp;">
if (!m_loaded || !m_paused)
	return SOME_ERROR;
m_paused = false;
// ... do resume stuff
</pre>
<p>When the MOD finishes playing, I needed something like this&#8230;</p>
<pre class="brush: cpp;">
// ... some code that checks for end
m_reachedEnd = true;
//ups... How about m_playing, m_paused?
//We need to change their values, so we don't break code elsewhere
m_playing = false;
m_pause = false;
</pre>
<p>And similar things when playing, stopping, etc.<br />
See the problems?</p>
<ul>
<li>We need checks for multiples variables</li>
<li>We need to make sure the variables have valid values in relation to each other</li>
<li>What if we want to add an extra state? For example, &#8220;bool m_fading&#8221;. We would need to examine a lot of code to check how the other variables are used, and hardwire this new one somewhere. Every time you need to add an extra variable, you&#8217;ll need to check more and more code to make sure everything is ok.</li>
</ul>
<p>Now look at the meaning of the variables. They are mostly mutually exclusive.</p>
<ul>
<li>If it&#8217;s playing, it can&#8217;t be paused and hasn&#8217;t reached the end.</li>
<li>If it&#8217;s paused, it&#8217;s not playing, and hasn&#8217;t reached the end yet.</li>
<li>&#8230; and so on&#8230;.</li>
</ul>
<p>The more data members a class has, the harder it gets to keep the object in a valid state, so, the less data to manage, the better. Less maintenance and less bugs.</p>
<p>One technique I use a lot when trying to simplify code is to look at it with state diagrams whenever possible.<br />
Here it is what happens (kind of) with instances of the MODModule class:</p>
<p><a title="mod_states.png" href="http://www.crazygaze.com/blog/wp-content/uploads/2007/12/mod_states.png"><img src="http://www.crazygaze.com/blog/wp-content/uploads/2007/12/mod_states.png" alt="mod_states.png" /></a></p>
<p>I can easily translate it to code with enums.</p>
<pre class="brush: cpp;">
enum MODState
{
    MOD_STATE_NOT_LOADED,
    MOD_STATE_STOPPED,
    MOD_STATE_PLAYING,
    MOD_STATE_PAUSED,
    MOD_STATE_REACHED_END
};

class MODModule
{
    // ...
    MODState m_state; // Now we have only one variable
};
</pre>
<p>This approach is a lot easier to maintain, and less error prone.<br />
Now the code in most functions become something like this:</p>
<p>To play&#8230;</p>
<pre class="brush: cpp;">
if (m_state!=MOD_STATE_STOPPED)
    return SOME_ERROR;
m_state = MOD_STATE_PLAYING;
// ... do play stuff
</pre>
<p>To pause&#8230;</p>
<pre class="brush: cpp;">
if (m_state!=MOD_STATE_PLAYING)
    return SOME_ERROR;
m_state = MOD_STATE_PAUSED;
// ... do pause stuff
</pre>
<p>To resume&#8230;</p>
<pre class="brush: cpp;">
if (m_state!=MOD_STATE_PAUSED)
    return SOME_ERROR;
m_state = MOD_STATE_PLAYING;
// ... do resume stuff
</pre>
<p>To stop&#8230;</p>
<pre class="brush: cpp;">
// We cannot stop if it's not even loaded yet, or it's already stopped
if (m_state==MOD_STATE_NOT_LOADED || m_state==MOD_STATE_STOPPED)
    return SOME_ERROR;
m_state = MOD_STATE_STOPPED;
// ... do stop stuff
</pre>
<p>The code may look similar, but it&#8217;s a lot less error prone, easier to follow and maintain.<br />
Looking at the State Diagram, I could easily squeeze in a &#8220;Fading&#8221; state and understand the conditions to enter or leave that state.</p>
<p>As a bonus, using enums will enforce more rules and help you out with errors the compiler might catch. Always prefer compile-time errors over run-time errors. <img src='http://www.crazygaze.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.crazygaze.com/blog/2007/12/19/simplifying-code-using-states/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

