<?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>wholesalealgorithms.com Blog</title>
	<atom:link href="http://wholesalealgorithms.com/blog9/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://wholesalealgorithms.com/blog9</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Thu, 24 Jun 2010 05:26:16 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>The Trouble with Templates</title>
		<link>http://wholesalealgorithms.com/blog9/2010/06/11/the-trouble-with-templates/</link>
		<comments>http://wholesalealgorithms.com/blog9/2010/06/11/the-trouble-with-templates/#comments</comments>
		<pubDate>Sat, 12 Jun 2010 03:45:26 +0000</pubDate>
		<dc:creator>matt</dc:creator>
				<category><![CDATA[Programming Style]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[stl]]></category>
		<category><![CDATA[template]]></category>

		<guid isPermaLink="false">http://wholesalealgorithms.com/blog9/?p=38</guid>
		<description><![CDATA[Don&#8217;t Misunderstand
My feelings about templates are often misunderstood &#8211; particularly by those who have known me long enough to remember the days when I swore that C++ had no place in video games.  That was when we had to fit the whole game into 2 megs of RAM, and we were doing things like squeezing the [...]]]></description>
			<content:encoded><![CDATA[<h2>Don&#8217;t Misunderstand</h2>
<p>My feelings about templates are often misunderstood &#8211; particularly by those who have known me long enough to remember the days when I swore that C++ had no place in video games.  That was when we had to fit the whole game into 2 megs of RAM, and we were doing things like squeezing the entire stack onto a 2 k scratch pad.  Those days were a long time ago.  Things have changed, and I have no desire to go back.</p>
<p>These days, C++ is the language of choice, and with that comes templates.  Template are powerful tools, and it would be foolish to dismiss them.  The opinions expressed here are not intended to discourage their use, but more to temper the exuberance with which many developers have embraced them.</p>
<h2>The Good Stuff</h2>
<p>Let me begin with some good reasons to consider templates as part of your software architecture.</p>
<p>The golden rule of programming is, &#8220;Don&#8217;t write the same code twice.&#8221;  I probably don&#8217;t need to justify that statement, but much to my amazement, I have run across some disagreement on that point.  The theory is simple.  Every time you repeat the same piece of code, you introduce a new chance of an error.  If you instead re-use a single function, any potential bugs in that function can be fixed in one place.</p>
<p>Templates allow us to carry this concept to the next level.  Simple functions can only be re-used if they are operating on the same type of object.  Templates allow us to abstract the algorithm being used to apply to a wide range of different methods.  By re-using a template rather than reproducing the algorithm with a new type, we reduce the number of different places where bugs can occur.  If a bug is discovered, the template can be corrected, and we can be assured that fix will be applied everywhere.  In contrast, the cut &amp; paste method will leave you pouring over your code looking for the same bug repeated elsewhere with no assurance that you&#8217;ll ever find them all.</p>
<h2>Unbridled Enthusiasm</h2>
<p>When programmers encounter their first template, their reaction is often one of distrust and skepticism.  But as you begin to get more comfortable with them, such fears tend to melt away.  Once the fear is gone, the promise that templates offer becomes very alluring, and it is easy to be taken in.  Naturally, it is those who are the most comfortable with templates that tend to use them the most, and it goes without saying that the authors behind your typical STL implementation are typically the most enthusiastic fans.</p>
<p>Like with all things in life, moderation is the key to a pattern of reliable success, and such enthusiasm can carry with it a price.  What price am I thinking of?</p>
<h2>Debugging STHELL</h2>
<p>I was hired onto one project primarily to do performace analysis and improvement, but when it came to debugging nasty crashes, I was available for that as well.  This team had fully embraced the STL paradigm, and no small number of their performance issues resulted from that, but what I want to point out here has more to do with the extreme difficulty of debugging issues that manifest themselves within STL.</p>
<p>In one case, I was called over to help analyze a crash, and I was so impressed by what I saw on the callstack that I copied it down.  Here is the top line from the callstack - completely unedited:</p>
<pre><span style="font-size:small;">default.exe!_STL::_Rb_tree&lt;TypedAssetId&lt;
FXShader::ExpressionEvaluator&gt;,
_STL::pair&lt;TypedAssetId&lt;FXShader::ExpressionEvaluator&gt; const ,
FXShader::ExpressionEvaluator *(__cdecl(FXShader::Effect&amp;)&gt;,
_STL::_Select1st&lt;_STL::pair&lt;TypedAssetId&lt;FXShader::
ExpressionEvaluator&gt; const ,FXShader::ExpressionEvaluator *
(__cdecl*)(FXShader::Effect &amp;)&gt; &gt;,
_STL::less&lt;TypedAssetId&lt;FXShader::ExpressionEvaluator&gt; &gt;,
_STL::allocator&lt;_STL::pair&lt;
TypedAssetId&lt;FXShader::ExpressionEvaluator&gt; const,
FXShader::ExpressionEvaluator * (__cdecl*)(FXShader::Effect &amp;)&gt; &gt; &gt;::
insert_unique(_STL::_Rb_tree_iterator&lt;_STL::pair&lt;
TypedAssetId&lt;FXShader::ExpressionEvaluator&gt; const ,
FXShader::ExpressionEvaluator * (__cdecl*)(FXShader::Effect &amp;)&gt;,
_STL::_Nonconst_traits&lt;_STL::pair&lt;
TypedAssetId&lt;FXShader::ExpressionEvaluator&gt; const ,
FXShader::ExpressionEvaluator * (__cdecl*)(FXShader::Effect &amp;)&gt; &gt; &gt;
* __position=0xffffffff,
const _STL::pair&lt;TypedAssetId&lt;FXShader::ExpressionEvaluator&gt; const ,
FXShader::ExpressionEvaluator * (__cdecl*)(FXShader::Effect &amp;)&gt;
&amp;__v={...})
line 476 + 0x8 bytes C++</span></pre>
<p>That&#8217;s a <strong>single</strong> function call, and the crash occurred somewhere within that function.  What on earth is that function?  A casual glance reveals that it clearly involves an STL Red-Black tree, and it has something to do with TypedAssetId and FXShader.  But that function signature is so out of control&#8230; this must be some really extreme case where someone is building up some serious template right?  Let&#8217;s take a look at that same line of code in the original C++:</p>
<pre><span style="font-size:small;">possibleUnitsMap[ unit.m_id ] = &amp;unit;</span></pre>
<p>That&#8217;s it.  This innocent-looking line of C++ translates into that incredible rat&#8217;s nest of STL &#8211; or as I like to call it, STHELL.  This is no exaggeration.  The example above was pasted directly out of the debugger &#8211; completely unedited.</p>
<p>Most programmers would scarcely dare to delve into that rat&#8217;s nest any deeper, but when you have a game that crashes, you have few options.  Somebody is going to have to study the situation, determine what has caused this crash, and use that information to formulate a solution.</p>
<p>We did find the cause, and we got the problem fixed, but the effort that was required was greatly increased by the complexity of the template implementation for what amounts to a simple map insertion.</p>
<h3>Speaking of Maps</h3>
<p>Here&#8217;s another example that just came up for me last week.  I was trying to figure out why the geometry was not appearing on my object in a timely fashion.  As I traced the problem, I ran across this simple line of code:</p>
<pre><span style="font-size:small;">return m_assetMap.find(guid, assetID);</span></pre>
<p>I fully expected to find my asset in the map, so when the search failed, my immediate reaction was to assume that I had not properly loaded it.  After tracing that problem through, I found that I had indeed loaded the asset and its <em>guid</em> was inserted into the map.  So why does the search fail?</p>
<p>At this point, you say to yourself, &#8220;well if your <em>guid</em> isn&#8217;t in the map, what <strong>is</strong> in the map?&#8221;  At least, that&#8217;s what I said to myself.  I had avoided doing this for days now, and there was simply nothing else for it.  It was time to debug the STL map.  Attempting to examine the map in the debugger is an exercise in futility.  Here&#8217;s what that looks like in the watch window:</p>
<pre><span style="font-size: small;">-m_assetMap
  -stlp_std::map&lt;lib::utf8string,lib::utf8string,
   stlp_std::less&lt;lib::utf8string&gt;,lib::CustomAllocator&lt;lib::utf8string&gt; &gt;
    -_M_t
      -stlp_std::priv::_Rb_tree_base&lt;stlp_std::pair
       &lt;lib::utf8string const ,lib::utf8string&gt;,
       lib::CustomAllocator&lt;lib::utf8string&gt; &gt;
        -_M_header
           lib::CustomAllocator&lt;stlp_std::priv::_Rb_tree_node
           &lt;stlp_std::pair&lt;lib::utf8string const ,lib::utf8string&gt; &gt; &gt;
        -_M_data
           _M_color false bool
          +_M_parent 0x14f89030
          +_M_left 0x03617d20
          +_M_right 0x14f89090
     _M_node_count 11
    +_M_key_compare {...}</span></pre>
<p>To get anything useful out of this data, you&#8217;re going to have to step into the template functions until you get deep enough that the debugger will actually understand what it&#8217;s looking at.  Tracing down into map&lt;&gt;::find() I eventually got into a place where the debugger could show me the strings being compared.  Here&#8217;s the callstack at that point.  (In this case, I have changed some namespaces to protect the <span style="text-decoration: line-through;">innocent</span> guilty.):</p>
<pre><span style="font-size: small;">lib::operator&lt;(const lib::utf8string &amp; lhs_utf8={...},
const lib::utf8string &amp; rhs_utf8={...})</span></pre>
<pre><span style="font-size: small;">stlp_std::less&lt;lib::utf8string&gt;::operator()(const lib::utf8string &amp; __x={...},
const lib::utf8string &amp; __y={...})</span></pre>
<pre><span style="font-size: small;">stlp_std::priv::_Rb_tree&lt;lib::utf8string,stlp_std::less&lt;lib::utf8string&gt;,
stlp_std::pair&lt;lib::utf8string const ,lib::utf8string&gt;,
stlp_std::priv::_Select1st&lt;stlp_std::pair&lt;lib::utf8string const ,lib::utf8string&gt; &gt;,
stlp_std::priv::_MapTraitsT&lt;stlp_std::pair&lt;lib::utf8string const ,lib::utf8string&gt; &gt;,
lib::CustomAllocator&lt;lib::utf8string&gt; &gt;::_M_find&lt;lib::utf8string&gt;
(const lib::utf8string &amp; __k={...})</span></pre>
<pre><span style="font-size: small;">stlp_std::priv::_Rb_tree&lt;lib::utf8string,stlp_std::less&lt;lib::utf8string&gt;,
stlp_std::pair&lt;lib::utf8string const ,lib::utf8string&gt;,
stlp_std::priv::_Select1st&lt;stlp_std::pair&lt;lib::utf8string const ,lib::utf8string&gt; &gt;,
stlp_std::priv::_MapTraitsT&lt;stlp_std::pair&lt;lib::utf8string const ,lib::utf8string&gt; &gt;,
lib::CustomAllocator&lt;lib::utf8string&gt; &gt;::find&lt;lib::utf8string&gt;
(const lib::utf8string &amp; __k={...})</span></pre>
<pre><span style="font-size: small;">stlp_std::map&lt;lib::utf8string,lib::utf8string,stlp_std::less&lt;lib::utf8string&gt;,
lib::CustomAllocator&lt;lib::utf8string&gt; &gt;::find&lt;lib::utf8string&gt;
(const lib::utf8string &amp; __x={...})</span></pre>
<pre><span style="font-size: small;">lib::map&lt;lib::utf8string,lib::utf8string,stlp_std::less&lt;lib::utf8string&gt; &gt;::
find(const lib::utf8string &amp; i_key={...}, lib::utf8string &amp; o_data={...})</span></pre>
<pre><span style="font-size: small;">FindAssetID(const lib::utf8string &amp; urn={...}, lib::utf8string &amp; physicalID={...})</span></pre>
<p>As I wade through my map element by element, eventually I did come across the <em>guid </em>I was looking for.  It seems the <em>guid</em> I was searching for was:</p>
<pre><span style="font-size: small;">guid:5075987e-0000-0000-0000-000000000000</span></pre>
<p>but the <em>guid </em>that had been inserted into the map was:</p>
<pre><span style="font-size: small;">guid:5075987e-0000-0000-0000-000000000000:modelformat</span></pre>
<p>Duh!  Why hadn&#8217;t I seen that right away?  /sarcasm off</p>
<h3>Breakpoints in STHELL</h3>
<p>As part of the typical debugging process, I like to go straight for breakpoints.  During the course of the above example, I naively attempted to insert a breakpoint onto line 552 of _tree.h on the line that says:</p>
<pre><span style="color: #0000ff; font-size: small;">if </span><span style="font-size: small;">(!_M_key_compare(_S_key(__x), __k))</span></pre>
<p>When I did that, Visual Studio became non-responsive.  After several minutes, it was eventually clear that with that single keystroke, I had inadvertently inserted 183 breakpoints.  The compiler will generate new instructions for every unique instance of the template it comes across.  Apparently there are 183 different permutations of _tree currently in this codebase.</p>
<p>Needless to say, breakpoints in the STL of a project like this one aren&#8217;t going to be very useful tools, and that&#8217;s a terrible price to have to pay.</p>
<h2>Summary</h2>
<p>So what should we do about this?  Should we swear off templates once and for all?  Outlaw STL?</p>
<p>Well I wouldn&#8217;t want to throw the baby out with the bathwater.  Templates are indeed powerful tools, and it would be foolish to dismiss them entirely.</p>
<h3>What about STL?</h3>
<p>STL is a handy suite of pre-built and pre-debugged containers.  They can save you a lot of development time up-front and they typically save you debugging time down the road.  If your application isn&#8217;t particularly speed-critical or sensitive to excessive memory fragmentation, STL is a great asset <strong>as long as you know what you&#8217;re doing</strong>.  I advise people to avoid STL in console game engines, but I find I am seldom heeded on that.  On the other hand, STL makes perfect sense for your tools.</p>
<h3>Curb Your Enthusiasm</h3>
<p>If you should ever find yourself in a position to reinvent an STL-like suite of templates, I urge you to remember those of us that will eventually have to decode the horrible mess the debugger is likely to make of your nested templates and specializations.  Readable code is a win for everybody, and we always need to weigh that against any potential benefits we would hope to gain by creating yet another template.</p>
]]></content:encoded>
			<wfw:commentRss>http://wholesalealgorithms.com/blog9/2010/06/11/the-trouble-with-templates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>That’s My Namespace. Don’t Wear it Out.</title>
		<link>http://wholesalealgorithms.com/blog9/2010/03/30/that%e2%80%99s-my-namespace-don%e2%80%99t-wear-it-out/</link>
		<comments>http://wholesalealgorithms.com/blog9/2010/03/30/that%e2%80%99s-my-namespace-don%e2%80%99t-wear-it-out/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 17:08:16 +0000</pubDate>
		<dc:creator>matt</dc:creator>
				<category><![CDATA[Programming Style]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[namespace]]></category>
		<category><![CDATA[using statement]]></category>

		<guid isPermaLink="false">http://wholesalealgorithms.com/blog9/?p=13</guid>
		<description><![CDATA[Namespaces can be used to resolve naming conflicts for classes or variables...At what point did it become good practice to create a new namespace for every layer of your hierarchy?..Namespaces prevent naming conflicts, but they do so at the cost of readability.]]></description>
			<content:encoded><![CDATA[<h2>Case In Point</h2>
<p>The game crashes, so you open up the debugger. You look at the callstack to see that the crash occurred in a function called:</p>
<pre><span style="color: #000080;">void DynamicButton::Activate()
{
    if (m_parent &amp;&amp; m_parent-&gt;IsValid(this))        // crash occurs here
        m_parent-&gt;DoSomething();
}</span></pre>
<p>Naturally you&#8217;re working with an optimized version, so the debugger&#8217;s idea of local variables is completely useless. According to the debugger, your <strong>this</strong> pointer is <strong>0xffffffff</strong>&#8230; Yeah right. This is no problem for you &#8211; you aren&#8217;t afraid of a little disassembly now are you? It&#8217;s a really simple function, so you quickly deduce that your <strong>this</strong> pointer was stored off in <strong>r31</strong> at the top of the function, and it is still valid at the time of the crash. So you go to the watch window and type:</p>
<pre><span style="color: #000080;">(DynamicButton*)r31</span></pre>
<p>That&#8217;ll do the trick certainly. But for some reason, the debugger won&#8217;t show you anything. It can&#8217;t seem to figure out what a <strong>DynamicButton</strong> is. How can this be? You&#8217;re looking at the source code right in front of you. Anyone can see that your this pointer is something called <strong>DynamicButton</strong>&#8230; or is it? Could it be your this pointer is actually something like this?</p>
<pre><span style="color: #000080;">(GameEngine::Interface::UIShared::UIController::UIButton::DynamicButton*)r31</span></pre>
<p>What the heck is going on here? The answer becomes clear only after you carefully scroll up through the source code and count up all the <strong>using</strong> commands sprinkled throughout.</p>
<h2>Good Reasons to Use Namespaces</h2>
<p>Don&#8217;t get me wrong, namespaces are a powerful and effective tool &#8211; especially for library development. Namespaces can be used to resolve naming conflicts for classes or variables. Naming conflicts don&#8217;t come up that often if you use reasonable names for things, but there are times when the inclusion of different library modules can introduce a naming conflict. Imagine you have a definition for <strong>class Quaternion</strong> in your math library. That&#8217;s pretty reasonable. In fact it is so reasonable, that it comes as no surprise that the author of your brand new animation library has a class called <strong>Quaternion</strong> too. Ideally, you&#8217;d both be sharing the same <strong>Quaternion</strong>, but sometimes that just isn&#8217;t possible. Not to worry. Just throw yours (or theirs or both) into a namespace and they no longer collide. Of course now your code doesn&#8217;t compile because you&#8217;ve referred to <strong>Quaternion</strong> everywhere, and it is now called <strong>MyNamespace::Quaternion</strong>. This is also easily solved. Just toss a little <strong>using namespace MyNamespace</strong> and all is well again.</p>
<p>This problem often comes up when you include libraries from different authors. Because of that, it is actually a good practice for library architects to enclose their stuff in a namespace.</p>
<h2>Bad Reasons to Use Namespaces</h2>
<p>At what point did it become good practice to create a new namespace for every layer of your hierarchy?</p>
<p>Namespaces prevent naming conflicts, but they do so at the cost of readability. When there is no chance of naming conflict, the namespace provides absolutely no benefit. Are we seriously worried that there might be another class called <strong>DynamicButton</strong> somewhere in the code? Ok I&#8217;ll give you that one. So <strong>Interface::DynamicButton</strong> still isn&#8217;t good enough? Ok <em>maybe</em> somebody has a namespace <strong>Interface</strong> there already? (We all know they don&#8217;t but what if they did?) I can see going all the way to:</p>
<pre><span style="color: #000080;">GameEngine::Interface::DynamicButton</span></pre>
<p>But this:</p>
<pre><span style="color: #000080;">GameEngine::Interface::UIShared::UIController::UIButton::DynamicButton</span></pre>
<p>&#8230;is just ridiculous.</p>
<h2>Why <em>Not</em> Use as Many Namespaces as I Can Think Of?</h2>
<p>It doesn&#8217;t hurt anything does it? Take my debugging example from above. That isn&#8217;t a made up story. That happened to me. The namespaces have been changed to protect the <span style="text-decoration: line-through;">innocent </span>guilty, but I am making no exaggeration.</p>
<h2>Don&#8217;t Hide Your Code</h2>
<p>Don&#8217;t forget the 80/20 rule. Most programmers spend 20% of their time writing code and 80% debugging code. Due to my particular specialty, I spend a great deal of time debugging other people&#8217;s code, and this gives me a unique perspective on things. The <strong>using</strong> statement hides the full name of the functions and variables, and that makes the detective work more difficult. Would you deliberately hide elements of your code from the other programmers on your team? (I suspect that some of you out there might actually answer &#8220;yes&#8221; to that. Why on earth would you do that? We&#8217;re trying to work together here, and that will go much easier if I can see what you&#8217;re doing.)</p>
<h2>What about readability?</h2>
<p>Longer variables and more words do not <em>necessarily</em> make your code more readable. Is &#8220;Moby Dick&#8221; more readable than &#8220;Horton Hears a Who&#8221;? Of course not. More words mean more <em>reading</em> not more <em>readability</em>. Once a single line of code no longer fits on the screen, it becomes dramatically more difficult to read. Consider our little debugging example. After discovering that there is in fact no such class as <strong>DynamicButton</strong>, we&#8217;ll probably want to take a look at the callstack window to see what it&#8217;s really called. What we see looks something like this:</p>
<pre><span style="color: #000080;">TheGame.exe!GameEngine::Interface::UIShared::UIController::UIButton::DynamicButton::Activate() line 437</span></pre>
<p>Or if your windows are arranged like mine, most of that will get cut off leaving you with something like this:</p>
<pre><span style="color: #000080;">TheGame.exe!GameEngine::Interface::UIShared::UICont</span></pre>
<p>Now you can clearly see the cost of all those namespaces.  You’ve effectively made the names of your variables and functions so long that they don’t fit on the screen anymore.  Obviously that isn’t going to work, so you’ve generously applied the <strong>using</strong> statement to allow you to shorten them to a more manageable size.  Those using statements are your acknowledgement that you really didn’t need such long variable names – at least not in <em>this</em> part of the code.</p>
<p>And that brings us to the real problem&#8230;</p>
<h2>Abusing the using</h2>
<p>The <strong>using</strong> statement in C++ shows all the hallmarks of an “afterthought.”</p>
<p>“We need a way to avoid naming conflicts.”  The <strong>namespace</strong> is born.</p>
<p>“Typing out the entire namespace all the time is a pain.”  The <strong>using</strong> statement is tacked on.</p>
<p>The real problem here is that <strong>using</strong> statements are not scoped.  For inexplicable reasons, the <strong>using</strong> statement is unlike virtually everything else in the C++ language.  It becomes active as soon as it is encountered and stays active until the end of the file.  There is no way to shut it off, and (at least at this point) completely opaque to debuggers.</p>
<p>This fact becomes painfully clear if you ever find yourself forced to put a <strong>using</strong> statement into a header file.  (I say “forced” because you certainly know better than to ever do this on purpose.)  Once you <strong>#include</strong> that header into your source file, that source file gets those <strong>using</strong> statements too.  If the whole point of the namespace was to avoid naming conflicts, how are you going to do that now that all your source files automatically get <strong>using</strong> statements in them, and you have no way to turn them off?</p>
<h2>Parting Thoughts</h2>
<p>I&#8217;ll leave you with this little tale.</p>
<p>It just happened to me again.</p>
<pre><span style="color: #000080;">void Viewport::UpdateCulling()
{
  DoTheOldStuff();
}</span></pre>
<p>I&#8217;m testing something new, and I need a way to enable/disable it easily. So I go into the code like this:</p>
<pre><span style="color: #000080;">bool gDoNewStuff = false;   //enable this to try the new way
void Viewport::UpdateCulling()
{
  if (gDoNewStuff)
    DoTheNewStuff();
  else
    DoTheOldStuff();
}</span></pre>
<p>Simple right? Just change the value of gDoNewStuff in the debugger to change the behavior of the code and see the results in realtime. Only what&#8217;s this? The debugger says:</p>
<pre><span style="color: #000080;">gDoNewStuff     CXX0030: Error: expression cannot be evaluated</span></pre>
<p>What happened? Did the compiler outsmart me and optimize out my global variable? It looks like it did, but wait&#8230; could it be&#8230; could my global variable actually be called:</p>
<pre><span style="color: #000080;">GameEngine::Renderer::Viewport::gDoNewStuff</span></pre>
<p>Sad? &#8230;Yes.</p>
<p>Funny? &#8230;Maybe.</p>
<p>True? &#8230;Absolutely.</p>
<p>It&#8217;s just not worth it.</p>
]]></content:encoded>
			<wfw:commentRss>http://wholesalealgorithms.com/blog9/2010/03/30/that%e2%80%99s-my-namespace-don%e2%80%99t-wear-it-out/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Asserts: Proper Care and Feeding</title>
		<link>http://wholesalealgorithms.com/blog9/2007/02/28/asserts-proper-care-and-feeding/</link>
		<comments>http://wholesalealgorithms.com/blog9/2007/02/28/asserts-proper-care-and-feeding/#comments</comments>
		<pubDate>Wed, 28 Feb 2007 21:50:49 +0000</pubDate>
		<dc:creator>matt</dc:creator>
				<category><![CDATA[Programming Style]]></category>
		<category><![CDATA[assert]]></category>
		<category><![CDATA[c++]]></category>

		<guid isPermaLink="false">http://wholesalealgorithms.com/blog9/2007/02/28/asserts-proper-care-and-feeding/</guid>
		<description><![CDATA[Vocabulary
First off, we need to agree on a common vocabulary. Language is how we communicate, and it only works when we all agree to the same meaning for the words. Dictionary.com offers this as a defintion for assert: &#8220;to state with assurance, confidence, or force; state strongly or positively; affirm.&#8221; That&#8217;s good background information, but [...]]]></description>
			<content:encoded><![CDATA[<h2>Vocabulary</h2>
<p>First off, we need to agree on a common vocabulary. Language is how we communicate, and it only works when we all agree to the same meaning for the words. <a class="external text" title="http://dictionary.reference.com/" rel="nofollow" href="http://dictionary.reference.com/">Dictionary.com</a> offers this as a defintion for <a class="external text" title="http://dictionary.reference.com/browse/assert" rel="nofollow" href="http://dictionary.reference.com/browse/assert">assert</a>: &#8220;to state with assurance, confidence, or force; state strongly or positively; affirm.&#8221; That&#8217;s good background information, but in the context of C++ we have a slightly more specific meaning. To avoid confusion when speaking to C++ programmers, we need look no further than &lt;<span class="SpellE">assert.h</span>&gt; for the definition we seek.</p>
<p>Simply put, assert is a macro which evaluates an expression and halts the program if the expression is false. The name of the file as well as the line number where the assert can be found are provided as output.</p>
<p>Yes you knew that already didn&#8217;t you? Of course you did. We all know what an assert is. Yet why do I keep hearing the phrase, &#8220;non-fatal assert?&#8221; We&#8217;ve agreed that an assert will halt the program. That&#8217;s what it does. So what would be the meaning of an assert that does not halt the program?</p>
<p>It is very reasonable to want to use some of the features of the assert macro for debugging purposes in a way that would not require the program to stop. Perhaps there is some sort of non-fatal glitch you want to monitor, but you don&#8217;t want to interfere with everyone else&#8217;s progress. You would like a macro that evaluates an expression and outputs the filename and line number if that expression is false but does not halt. This is a great idea. I would suggest that we refer to such conditions as <em>warnings</em> so that they are not confused with <em>asserts</em>.</p>
<h2>Asserts are Not Break-Points</h2>
<p>Where people start to really go wrong with their asserts is when they overuse them. Many years ago, I was working on a game with one other engineer &#8211; a perfectly competent one at that. One day a designers came to me because his game was crashing every time he tried to go to a particular area of the map &#8211; naturally the area where he was working that day. I tried it for myself and found that the crash he was experiencing was actually an assert. With only the 2 programmers on the team, it wasn&#8217;t too hard to find the right guy to ask about this. When I pointed it out to him, he replied, &#8220;Oh, that&#8217;s just there for debugging, you can go ahead and step over that.&#8221;</p>
<p>Seems he was looking for some sort of bug, and he was using asserts sprinkled all over to try to catch it. Clearly this bug wasn&#8217;t so severe that it was going to cause major problems without the assert because he had just told me to skip over the assert.</p>
<p>I should not have to say this, but this is not the correct way to use asserts. In this case, the programmer had managed to turn a minor bug into a progression-blocker that had already wasted multiple man-hours of designer time not to mention the time I had also wasted on it already.</p>
<p>Do all of your artists and designers run with debuggers open so they can &#8220;step-over&#8221; your asserts? Yeah mine don&#8217;t either. Do the other programmers on the team know which asserts are important and which are just your own personal experiment? How would they?</p>
<h2>Do Not Allow Asserts to be Skipped</h2>
<p>As I said, this example shows how the really catastrophic assert abuse gets started, but that&#8217;s only the beginning. What happens next goes something like this&#8230;</p>
<ol>
<li>There are asserts in the code which are otherwise non-fatal (such as in the above example).</li>
<li>The rest of the team must not be blocked by innocuous asserts.</li>
<li>We must therefore set up a way for asserts to be skipped-over!</li>
</ol>
<p>Brilliant! Oh, and you thought you were a genius for coming up with that one first right? Well congratulations, you&#8217;ve just broken asserts. Once you implement this lovely new feature, asserts will immediately start becoming more and more useless.</p>
<p>Don&#8217;t agree? Here&#8217;s how it goes. Once asserts can be skipped over, they are no longer a progression blocker. This gives you a license to put asserts in wherever you want to with no worries that it will prevent anyone from getting their work done. So what happens next is asserts start going in where warnings belong. The team will start using asserts to warn artists and designers about mistakes they seem to have made:</p>
<pre>assert(pFrog-&gt;pLilyPad);  // the frog must have a lily pad!
assert(hitPoints &gt; 0);    // monsters must have hit points!
// make sure your triangle is not degenerate!
assert(vertex[0].x != vertex[1].x || vertex[1].x != vertex[2].x
|| vertex[0].y != vertex[1].y || vertex[1].y != vertex[2].y
|| vertex[0].z != vertex[1].z || vertex[1].z != vertex[2].z);</pre>
<p>Ok so I made up the lily pad bit, but the degenerate triangle is one I&#8217;ve actually run across before.</p>
<p>Still don&#8217;t see the problem? The designers get warned every time they create a frog and forget to give him a lily pad. Sounds great right? In practice, you don&#8217;t have a serious problem yet. Like hair in your shower drain, it takes a while for the clog to really build up.</p>
<p>The way it happens is so simple, it&#8217;s almost hard to believe it could become a problem. One day an artist is working happily along and he gets an assert because some frog doesn&#8217;t have a lily pad. &#8220;Not my problem,&#8221; he says to himself. He quietly hits the &#8220;ignore it&#8221; button and moves on. And then he ignores the next one, and the next until before long, there are so many of them that he no longer even pays any attention to them at all. Now he will silently click right past the assert that was intended for him to see and take no action to fix it.</p>
<p>There&#8217;s a certain critical mass of error messages that gets reached at some point, and once you hit it, all error messages become just another line of spam to be ignored as they scroll past glazed-over eyes. This critical mass is different for everybody, but the key factor to remember is that it is invariably lower for the end-user than it is for the programmer. For many non-technical people, I would guess this critical mass may be as low as 2 errors per run. In fact, if a non-technical person becomes accustomed to seeing 2 errors every run, I would hazard a guess that it would become very unlikely that they would even notice a 3rd error should it suddenly appear. Once you&#8217;ve added that &#8220;ignore it&#8221; button, that&#8217;s exactly what will happen &#8211; people will start to ignore your errors.</p>
<p>If you&#8217;re one of those people who still doesn&#8217;t see the problem, you&#8217;re probably thinking something like, &#8220;It&#8217;s not my fault if people ignore errors that are right in front of them. They need to pay attention to those.&#8221;</p>
<p>If you&#8217;re still thinking that way, then consider this: Just how bad could it get?</p>
<h2>How Bad Could It Get?</h2>
<p>Imagine the scenerio I described is allowed to go unchecked for a little while. Imagine a team of 100 (30 of whom are programmers) working together for 2 years under the philosophy that every conceivable error will have an assert on it. Now imagine you are dropped into the midst of that team. Perhaps you are a new hire, or maybe you are a temporary contractor brought on for some last-minute optimization. What might this project be like?</p>
<p>I&#8217;ll give you a real-world example. Without naming names, I have seen an actual video game project where booting into the first level of the game from a cold start results in 17 unique asserts with another 11 over the course of playing that first level. I tried to count the total number of occurances, but after getting 20 instances of the first assert, I gave up and punched the &#8220;ignore this assert&#8221; button. Hard to believe? This is a true story, and I&#8217;m not talking about early in development. This project was post-beta at the time I performed this test.</p>
<p>So when you find yourself dealing with this, what&#8217;s the first thing you do? That&#8217;s right &#8211; you figure out a way to disable asserts altogether. Only now you find yourself asking, &#8220;what do I do when I actually <em>want</em> an assert?&#8221; Well you&#8217;ll probably eventually break down and create a new assert macro. Maybe this time you&#8217;ll call it &#8220;crash&#8221; because the assert doesn&#8217;t crash anymore, and you want to be sure yours does. In fact this same project I&#8217;m talking about already has a crash() macro. I&#8217;ll give you one guess what that macro does. If you guessed &#8220;it crashes,&#8221; sorry, but thanks for playing. Once upon a time it crashed, but at some point, the brain-trust who decided that asserts should be skippable came along and &#8220;fixed&#8221; crash() too. On this project, crash() merely logs the event to a text file and happily moves on without a blip &#8211; completely unnoticed.</p>
<h2>Improved Asserts</h2>
<p>Don&#8217;t get me wrong, there are ways to legitimately improve the assert macro. Just remember not to alter the fundamentals we agreed on for the definition of &#8220;assert&#8221;.</p>
<ol>
<li>Evaluate an expression</li>
<li>Halt the program if the expression is false</li>
<li>Provide the location of the assert</li>
</ol>
<p>So what are some ways to improve the simple assert?</p>
<ul>
<li><strong>Warnings</strong> The first thing you should do is create that warning() macro so that people are not tempted to use asserts for non-fatal issues. I urge you for all of our sakes please do not call your warning macro assert_nonfatal. Don&#8217;t perpetuate the idea that asserts can in any way be non-fatal.</li>
<li><strong>Messages</strong> The standard assert will echo back only the expression, the filename, and the line number. These are likely to mean absolutely nothing to the end user. Adding a meaningful string to the assert will help the team bring it to the correct programmer&#8217;s attention faster. I like to use a little macro assert_msg(expression, message) for that.
<ul>
<li><strong>Author</strong> These asserts must be addressed by programmers &#8211; you aren&#8217;t using asserts to remind designers to give their frogs lily pads right? So the only important part of the assert message is which programmer needs to know about it. I know of one company where they have created special assert macros with the initials of the programmer on it like assert_mrw(expression). When one of these goes off, it tells the victim which programmer to go talk to.</li>
</ul>
</li>
<li><strong>On-Screen Displays</strong> I mostly work on consoles, and some consoles don&#8217;t provide text output outside of the debugger. What that means is artists, designers, and even testers will get an assert and be unable to see the text. The assert is there to provide valuable information about the crash, so in these situations, it is worth the effort to print the relevant information on the display in addition to the text output before breaking.</li>
<li><strong>Unconditional Asserts</strong> I see these all the time, and to be honest they bug me, but there&#8217;s technically nothing wrong with them so enjoy yourself. If you&#8217;d prefer to type assert_unconditional() instead of assert(0), well that&#8217;s your choice. You won&#8217;t catch me doing it.</li>
</ul>
<h2>Summary</h2>
<p>Asserts are really very simple as long as we all agree on what they mean and use them correctly. If you maintain a strict difference between a warning and an assert, your project will run smoothly.</p>
<p>You may still be sitting there saying, &#8220;this will never happen to me because we won&#8217;t let it get that bad.&#8221; Maybe you&#8217;re right, but I think it comes down to a matter of philosophy. If you have a philosophy at your organization where it&#8217;s ok to misuse asserts, you should expect them to be misused.</p>
]]></content:encoded>
			<wfw:commentRss>http://wholesalealgorithms.com/blog9/2007/02/28/asserts-proper-care-and-feeding/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.448 seconds -->
