<?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>PHP in Action &#187; Clean code</title>
	<atom:link href="http://blog.agilephp.com/category/clean-code/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.agilephp.com</link>
	<description>Dagfinn Reiersøl on PHP, agile development, Ruby and other addictive substances</description>
	<lastBuildDate>Mon, 28 Sep 2009 14:35:32 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Bad code is good for you?</title>
		<link>http://blog.agilephp.com/2009/09/28/bad-code-is-good-for-you/</link>
		<comments>http://blog.agilephp.com/2009/09/28/bad-code-is-good-for-you/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 12:08:43 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[Application design]]></category>
		<category><![CDATA[Clean code]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Domain-Driven Design]]></category>
		<category><![CDATA[Open source]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.agilephp.com/?p=1630</guid>
		<description><![CDATA[



Image by Balakov via Flickr



In The importance of bad code (or, WordPress and why I am a psychic), Marco Tabini proposes the idea that we need bad code. Or at least that we should be tolerant of bad code in open source projects because that invites participants that might otherwise not contribute.
This is an interesting [...]]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img" style="margin: 1em; display: block;">
<div>
<dl class="wp-caption alignleft" style="width: 250px;">
<dt class="wp-caption-dt"><a href="http://www.flickr.com/photos/71447254@N00/1544234007"><img title="Spaghetti Code" src="http://farm3.static.flickr.com/2257/1544234007_dd7686d788_m.jpg" alt="Spaghetti Code" width="240" height="155" /></a></dt>
<dd class="wp-caption-dd zemanta-img-attribution" style="font-size: 0.8em;">Image by <a href="http://www.flickr.com/photos/71447254@N00/1544234007">Balakov</a> via Flickr</dd>
</dl>
</div>
</div>
<p>In <a href="http://mtabini.blogspot.com/2009/09/importance-of-bad-code-or-wordpress-and.html">The importance of bad code (or, WordPress and why I am a psychic)</a>, Marco Tabini proposes the idea that we <em>need</em> bad code. Or at least that we should be tolerant of bad code in open source projects because that invites participants that might otherwise not contribute.</p>
<p>This is an interesting idea that struck me as novel. But after thinking more about it, I believe it&#8217;s not a radical departure from what we&#8217;re all implicitly accepting, no matter how fanatical we might be about clean code.</p>
<p><span id="more-1630"></span></p>
<p><a class="zem_slink" title="Luke Welling" rel="wikipedia" href="http://en.wikipedia.org/wiki/Luke_Welling"> Luke Welling</a>&#8217;s comment to the blog post is particularly enlightening and worth quoting in full:</p>
<blockquote><p>I&#8217;d argue that bad code is often a sign and a side effect of a thriving, welcoming user community around a project.</p>
<p>The OSS projects with good code tend to have a relatively small group of committers doing nearly all the work. There is a big learning curve to<br />
working within the project&#8217;s (probably unwritten) architectural guidelines, and a big reputation curve that a new person has to climb<br />
to get their patches accepted.</p>
<p>Bad code is often a sign of welcoming new contributors, taking patches that do something useful even if the approach is ugly.</p>
<p>We  all know the problems bad code brings, but I would argue that some  projects are not just successful in spite of bad code, but successful  because they allow bad code.</p></blockquote>
<p>I commented:</p>
<blockquote><p>If  we&#8217;re looking for the optimal strategy (which is likely to depend a lot  on the specific project), the question may be what parts of the code  need to be held to high quality standards, and what parts don&#8217;t require such strictness. And how to separate the two. Security is one of the key issues, since bugs can hide in bad code, and some of those will be security bugs.</p></blockquote>
<p>Perhaps even more important is the question of whether and how to keep a clean separation between good and bad code. Bad code becomes a problem to me mainly when I need to maintain bad code written by others. Not that I dislike it so much; I sometimes enjoy cleaning up messes, but it slows me down. But if the person who wrote it is maintaining it, it doesn&#8217;t affect me much. So a clean separation would be helpful.</p>
<p>That also makes the whole issue clearer to me. Most of us use operating systems, library software and applications that aren&#8217;t necessarily up to our coding standards. Having lower code quality in parts of a project is not much different in principle. In fact, it may be less of a problem in some cases. When you a program library that has code of poor quality, the good code is dependent on that bad code. If you are programming the core of an open-source project and someone else is adding bad code in the form of an extension, the bad code is dependent on the good code, making it even less likely that the bad code can affect the good code.</p>
<p>In <a class="zem_slink" title="Domain-driven design" rel="wikipedia" href="http://en.wikipedia.org/wiki/Domain-driven_design">Domain-Driven Design</a>, there is a pattern called Anti-Corruption Layer which can be helpful in preventing the bad code from having an undue influence on the structure of the good code. It&#8217;s worth thinking about, especially when the bad code has an illogical and confusing API.</p>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Reblog this post [with Zemanta]" href="http://reblog.zemanta.com/zemified/eb6b55e2-85da-88bd-a263-dc329004c320/"><img class="zemanta-pixie-img" style="border: medium none; float: right;" src="http://img.zemanta.com/reblog_a.png?x-id=eb6b55e2-85da-88bd-a263-dc329004c320" alt="Reblog this post [with Zemanta]" /></a><span class="zem-script more-related pretty-attribution"><script src="http://static.zemanta.com/readside/loader.js" type="text/javascript"></script></span></div>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=PHP%20in%20Action&amp;siteurl=http%3A%2F%2Fblog.agilephp.com%2F&amp;linkname=Bad%20code%20is%20good%20for%20you%3F&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F09%2F28%2Fbad-code-is-good-for-you%2F"><img src="http://blog.agilephp.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://blog.agilephp.com/2009/09/28/bad-code-is-good-for-you/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t refactor without unit tests</title>
		<link>http://blog.agilephp.com/2009/09/03/dont-refactor-without-unit-tests/</link>
		<comments>http://blog.agilephp.com/2009/09/03/dont-refactor-without-unit-tests/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 13:56:49 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[Clean code]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit testing]]></category>

		<guid isPermaLink="false">http://blog.agilephp.com/?p=1596</guid>
		<description><![CDATA[



Image by niallkennedy via Flickr



Brandon Savage is writing a series on code improvement using a code example (starting with Peer Review: Taking Code And Making It Better). In other words, it&#8217;s about refactoring, which is practically my favorite subject. Although I don&#8217;t agree with all of it, it&#8217;s mostly good advice. I recommend it.
That said, [...]]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img" style="margin: 1em; display: block;">
<div>
<dl class="wp-caption alignleft" style="width: 250px;">
<dt class="wp-caption-dt"><a href="http://www.flickr.com/photos/35034351734@N01/330227455"><img title="Google &quot;Testing on the Toilet&quot;" src="http://farm1.static.flickr.com/155/330227455_738b83c72e_m.jpg" alt="Google &quot;Testing on the Toilet&quot;" width="240" height="79" /></a></dt>
<dd class="wp-caption-dd zemanta-img-attribution" style="font-size: 0.8em;">Image by <a href="http://www.flickr.com/photos/35034351734@N01/330227455">niallkennedy</a> via Flickr</dd>
</dl>
</div>
</div>
<p>Brandon Savage is writing a series on code improvement using a code example (starting with <a href="http://www.brandonsavage.net/peer-review-taking-code-and-making-it-better/">Peer Review: Taking Code And Making It Better</a>). In other words, it&#8217;s about <a class="zem_slink" title="Code refactoring" rel="wikipedia" href="http://en.wikipedia.org/wiki/Code_refactoring">refactoring</a>, which is practically my favorite subject. Although I don&#8217;t agree with all of it, it&#8217;s mostly good advice. I recommend it.</p>
<p>That said, I do have something important to add. The series is missing the first, most basic rule: Don&#8217;t refactor unless you have good automated test coverage (typically with <a class="zem_slink" title="Unit testing" rel="wikipedia" href="http://en.wikipedia.org/wiki/Unit_testing">unit tests</a>). And if there are no test, write them before you start refactoring. If you don&#8217;t, you&#8217;ll make mistakes and get lost in a frustrating bug search, unless you&#8217;re very stingy and don&#8217;t refactor too much. With test coverage, you have freedom to experiment, to change something and change it back if you don&#8217;t like the result. This, above all, is what makes refactoring such a great learning experience.</p>
<p>Some of those who have commented on the post <a href="http://www.brandonsavage.net/peer-review-looking-into-abstraction/">Peer Review: Looking Into Abstraction</a> (Greg Beaver, Jeff Carouth) mention testing and point out the need to inject objects so that they can be replaced with mock objects for testing. This is a wise move, and practically unavoidable in this case. To support refactoring, unit tests need to be run frequently, without accessing outside services (twitter or email in this case) that take time to process.</p>
<p>This means that in this case, it&#8217;s actually necessary to refactor a bit before proper unit tests can be implemented. This is what Michael Feathers calls the <em>Legacy Code Dilemma</em> in his book <a href="http://www.amazon.com/gp/product/0131177052?ie=UTF8&amp;tag=phinac-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0131177052">Working Effectively with Legacy Code</a><img class=" lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz lmfwcewjbjvyqgtkyshz wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm wjtwchqpuszatsnifmwm" style="border: medium none  ! important; margin: 0px ! important;" src="http://www.assoc-amazon.com/e/ir?t=phinac-20&amp;l=as2&amp;o=1&amp;a=0131177052" border="0" alt="" width="1" height="1" />. Certainly building this dilemma into new code is not a good idea. Make the code unit-testable before it&#8217;s too late.</p>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Reblog this post [with Zemanta]" href="http://reblog.zemanta.com/zemified/20aff681-c4c1-8462-a15b-12d73157b0de/"><img class="zemanta-pixie-img" style="border: medium none; float: right;" src="http://img.zemanta.com/reblog_a.png?x-id=20aff681-c4c1-8462-a15b-12d73157b0de" alt="Reblog this post [with Zemanta]" /></a><span class="zem-script more-related pretty-attribution"><script src="http://static.zemanta.com/readside/loader.js" type="text/javascript"></script></span></div>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=PHP%20in%20Action&amp;siteurl=http%3A%2F%2Fblog.agilephp.com%2F&amp;linkname=Don%26%238217%3Bt%20refactor%20without%20unit%20tests&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F09%2F03%2Fdont-refactor-without-unit-tests%2F"><img src="http://blog.agilephp.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://blog.agilephp.com/2009/09/03/dont-refactor-without-unit-tests/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Real programming with PHP 5.3 (part 3): Links</title>
		<link>http://blog.agilephp.com/2009/04/12/real-programming-with-php-53-part-3-links/</link>
		<comments>http://blog.agilephp.com/2009/04/12/real-programming-with-php-53-part-3-links/#comments</comments>
		<pubDate>Sun, 12 Apr 2009 21:14:54 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[Application design]]></category>
		<category><![CDATA[Clean code]]></category>
		<category><![CDATA[JavaScript/Ajax]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[PHP 5.3]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Links]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.agilephp.com/?p=1547</guid>
		<description><![CDATA[



Image via Wikipedia



After the previous post in this series, additional independent implementations of the idea of JavaScript-style classes have turned up. So I&#8217;m going to list them and comment briefly on the differences. I hope this will be helpful to anyone who actually wants to use this in practice and needs to decide on the [...]]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img" style="margin: 1em; display: block;">
<div>
<dl class="wp-caption alignright" style="width: 210px;">
<dt class="wp-caption-dt"><a href="http://commons.wikipedia.org/wiki/Image:Linking_Number_2.svg"><img title="Two curves with linking number 2." src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/0e/Linking_Number_2.svg/200px-Linking_Number_2.svg.png" alt="Two curves with linking number 2." height="121" width="200"></a></dt>
<dd class="wp-caption-dd zemanta-img-attribution" style="font-size: 0.8em;">Image via <a href="http://commons.wikipedia.org/wiki/Image:Linking_Number_2.svg">Wikipedia</a></dd>
</dl>
</div>
</div>
<p>After the previous post in this series, additional independent implementations of the idea of JavaScript-style classes have turned up. So I&#8217;m going to list them and comment briefly on the differences. I hope this will be helpful to anyone who actually wants to use this in practice and needs to decide on the details of the implementation. Here are the links in chronological order:</p>
<ul>
<li><a href="http://www.sitepoint.com/forums/showthread.php?t=565576">Ionut G. Stan:Javascript style PHP with PHP 5.3.0 (forum posting).</a></li>
<li><a href="http://loveandtheft.org/2008/09/20/javascript-oo-python-ducktyping-in-php53/">Fredrik Holmström: Javascript-OO &amp; Python-DuckTyping in PHP5.3.</a></li>
<li><a href="http://www.ibm.com/developerworks/opensource/library/os-php-5.3new2/index.html">John Mertic: What&#8217;s new in PHP V5.3, Part 2: Closures and lambda functions.</a></li>
<li><a href="http://blog.agilephp.com/2009/03/31/real-programming-with-php-53-part-2-javascript-style-classes/">My own previous article.</a></li>
<li><a href="http://webreflection.blogspot.com/2009/03/jsphp-javascript-object-like-php-class.html">Andrea Giammarchi: A JavaScript Object Like PHP Class.</a></li>
</ul>
<p>One difference is how JavaScript-like the implementations are. Some of them implement a syntax that is deliberately made to resemble JavaScript.  Andrea Giammarchi&#8217;s version even uses ArrayAccess to make it possible to access object properties using both object and array syntax, as in JavaScript. At the other extreme is my implementation. I&#8217;ve tried to make it as similar to a regular PHP class as possible. You can instantiate an object in the same way as with an ordinary PHP class. This comes from defining the methods inside the class constructor.</p>
<p>After seeing all of these, I prefer my own way of doing it, except that it lacks what I mentioned in the previous article: an exception when you try to call an unrecognized method. But I&#8217;m obviously not objective, and I may have have missed something.</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=PHP%20in%20Action&amp;siteurl=http%3A%2F%2Fblog.agilephp.com%2F&amp;linkname=Real%20programming%20with%20PHP%205.3%20%28part%203%29%3A%20Links&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F04%2F12%2Freal-programming-with-php-53-part-3-links%2F"><img src="http://blog.agilephp.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://blog.agilephp.com/2009/04/12/real-programming-with-php-53-part-3-links/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>One behavior != one assertion</title>
		<link>http://blog.agilephp.com/2009/02/21/one-behavior-one-assertion/</link>
		<comments>http://blog.agilephp.com/2009/02/21/one-behavior-one-assertion/#comments</comments>
		<pubDate>Sat, 21 Feb 2009 21:07:24 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[Clean code]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Behavior Driven Development]]></category>
		<category><![CDATA[Unit Tests]]></category>

		<guid isPermaLink="false">http://blog.agilephp.com/?p=1483</guid>
		<description><![CDATA[



Image by libbyrosof via Flickr



The debate on the &#8220;one assertion&#8221; principle continues. Pádraic Brady and I agree on the general principle, but since he is so categorical in his second article, I needed to inspect his reasoning more closely. It&#8217;s clear that our disagreement is more than superficial. The more I think about it, the [...]]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img" style="margin: 1em; display: block;">
<div>
<dl class="wp-caption alignleft" style="width: 250px;">
<dt class="wp-caption-dt"><a href="http://www.flickr.com/photos/87251222@N00/2884366929"><img title="balkan naci islimyeli strait jacket" src="http://farm4.static.flickr.com/3224/2884366929_c8db1c6daa_m.jpg" alt="balkan naci islimyeli strait jacket" width="240" height="196" /></a></dt>
<dd class="wp-caption-dd zemanta-img-attribution" style="font-size: 0.8em;">Image by <a href="http://www.flickr.com/photos/87251222@N00/2884366929">libbyrosof</a> via Flickr</dd>
</dl>
</div>
</div>
<p style="margin-bottom: 0cm;">The debate on the &#8220;one assertion&#8221; principle continues. Pádraic Brady and I agree on the general principle, but <a href="http://blog.astrumfutura.com/archives/388-Unit-Testing-One-Test,-One-Assertion-Why-It-Works.html">since he is so categorical in his second article</a>, I needed to inspect his reasoning more closely. It&#8217;s clear that our disagreement is more than superficial. The more I think about it, the more I disagree.</p>
<h2 style="margin-bottom: 0cm;">The state of the art</h2>
<p style="margin-bottom: 0cm;">Pádraic maintains that one assertion per test is a rule that should always be followed unless there is a specific good reason to break it. I prefer it as a guideline, as does Robert C. Martin in the book <a href="http://www.amazon.com/gp/product/0132350882?ie=UTF8&amp;tag=phinac-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0132350882">Clean Code</a>. The reference is not intended as an appeal to authority to &#8220;prove&#8221; that I&#8217;m right. I&#8217;m just making the point that I think this reflects the current state of the art, which is not necessarily perfect, of course.</p>
<h2 style="margin-bottom: 0cm;">How small is a behavior?</h2>
<p style="margin-bottom: 0cm;">So what is the basis for wanting to enforce this principle as a strict rule? Pádraic<span style="font-style: normal;"> claims that &#8220;1 behavior == 1 assertion&#8221;.</span></p>
<p style="margin-bottom: 0cm;"><span style="font-style: normal;"><br />
</span></p>
<p style="margin-bottom: 0cm; font-style: normal;"><span style="font-style: normal;">How does that make sense? </span>The starting point is <a class="zem_slink" title="Behavior Driven Development" rel="wikipedia" href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">Behavior-Driven Development</a> (BDD). I agree with the BDD principle that one test should test one behavior—as a guideline. It&#8217;s makes tests more focused, more readable and makes for better error messages when tests fail. Above all, it forces you to <em>think</em><span style="font-style: normal;"> about what is a behavior and what is not. And the idea of one assertion per test drives that thinking process.</span></p>
<p style="margin-bottom: 0cm; font-style: normal;"><span style="font-style: normal;"><br />
</span></p>
<p style="margin-bottom: 0cm; font-style: normal;">From that point of view, &#8220;1 behavior == 1 assertion&#8221; seems totally logical. Unfortunately, it misses the point. It introduces a mechanical equivalence that negates the very thinking process I was just advocating. It makes the conceptual notion of a single, atomic behavior dependent on syntax and on the implementation specifics of a test framework.</p>
<p style="margin-bottom: 0cm; font-style: normal;">
<p style="margin-bottom: 0cm; font-style: normal;">For example, let&#8217;s say we want to test that a product object represents a certain model, a Logitech Harmony One remote control.</p>
<pre class="brush: php">
$this-&gt;assertEquals(&#039;Logitech&#039;, $product-&gt;make);
$this-&gt;assertEquals(&#039;Harmony One&#039;, $product-&gt;model);
</pre>
<p>It&#8217;s two assertions, but we&#8217;re only testing for one thing. We just want to make sure this product is what it should be and not something else. But let&#8217;s think some more about it. There are several ways we could make this into one assertion instead of two. This one, for instance:</p>
<pre class="brush: php">

$this-&gt;assertTrue(
&#039;Logitech&#039; == $product-&gt;make  &amp;amp;&amp;amp;  &#039;Harmony One&#039; == $product-&gt;model);
</pre>
<p>Not very pretty, is it? I think we can agree that this is not an improvement. More importantly, it doesn&#8217;t change the nature of what we are testing. We didn&#8217;t change <em>what</em> we&#8217;re testing, we just changed the way we express the test. A better way to get one assertion would be to make a custom assertion method such as assertLogitechHarmonyOne(). That would be more readable, but it wouldn&#8217;t help our statistics. The test framework would still see two assertions and report this as a 1 to 2 relationship between tests and assertions. And again, what we&#8217;re testing remains the same.</p>
<p>It gets worse. We&#8217;re testing one thing, but are we testing one behavior? No, we&#8217;re just testing the outcome. This is another logical flaw in the &#8220;1 behavior == 1 assertion&#8221; equivalence. A behavior is not tested by assertions, it&#8217;s tested by a complete test method. What happens before the assertions also counts, obviously. You could have multiple behaviors in the test with a single outcome that could be tested by a single assertion.</p>
<p>But I haven&#8217;t mentioned the simplest way to get one assertion per test. Just delete all assertions but one. It&#8217;s cheating, and problably toxic the quality of your tests, but it satisfies the criterion and generates good-looking statistics. It&#8217;s the thing that&#8217;s bound to happen if you try to force this on developers.</p>
<p>Better not use the &#8220;one assertion&#8221; principle as a strait jacket. It works better as exercise equipment to jog your mind.</p>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Zemified by Zemanta" href="http://reblog.zemanta.com/zemified/fd558844-2fd4-411a-aa77-6613d27ea6ba/"><img class="zemanta-pixie-img" style="border: medium none; float: right;" src="http://img.zemanta.com/reblog_a.png?x-id=fd558844-2fd4-411a-aa77-6613d27ea6ba" alt="Reblog this post [with Zemanta]" /></a></div>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=PHP%20in%20Action&amp;siteurl=http%3A%2F%2Fblog.agilephp.com%2F&amp;linkname=One%20behavior%20%21%3D%20one%20assertion&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F02%2F21%2Fone-behavior-one-assertion%2F"><img src="http://blog.agilephp.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://blog.agilephp.com/2009/02/21/one-behavior-one-assertion/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>One assertion per test—always?</title>
		<link>http://blog.agilephp.com/2009/02/15/one-assertion-per-test%e2%80%94always/</link>
		<comments>http://blog.agilephp.com/2009/02/15/one-assertion-per-test%e2%80%94always/#comments</comments>
		<pubDate>Sun, 15 Feb 2009 19:53:02 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[Clean code]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Tests]]></category>

		<guid isPermaLink="false">http://blog.agilephp.com/?p=1468</guid>
		<description><![CDATA[



Image via Wikipedia



Pádraic Brady pleads for the principle that a unit test method should have only one assertion. His point is perfectly valid; there are several good reasons why one assertion per method is a smart guideline when writing unit tests. But since he drags up the term &#8220;lazy&#8221;, I feel the need for soul-searching [...]]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img" style="margin: 1em; display: block;">
<div>
<dl class="wp-caption alignleft" style="width: 212px;">
<dt class="wp-caption-dt"><a href="http://commons.wikipedia.org/wiki/Image:Louis_the_Pious.jpg"><img title="Louis the Pious doing penance at Attigny in 822" src="http://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Louis_the_Pious.jpg/202px-Louis_the_Pious.jpg" alt="Louis the Pious doing penance at Attigny in 822" width="202" height="186" /></a></dt>
<dd class="wp-caption-dd zemanta-img-attribution" style="font-size: 0.8em;">Image via <a href="http://commons.wikipedia.org/wiki/Image:Louis_the_Pious.jpg">Wikipedia</a></dd>
</dl>
</div>
</div>
<p><span class="fn">Pádraic Brady</span><span class="plugin_comment_author"> <a href="http://blog.astrumfutura.com/index.php?url=archives/387-Unit-Testing-Multiple-Assertions-And-LazyShallow-Testing-Are-Evil.html">pleads for the principle that a unit test method should have only one assertion</a>. His point is perfectly valid; there are several good reasons why one assertion per method is a smart guideline when writing unit tests. But since he drags up the term &#8220;lazy&#8221;, I feel the need for soul-searching and confession.</span></p>
<p>The average for my current unit tests still hovers around three or four assertions per test method. And when I think about it, I see that the reason is that I&#8217;m not always taking the time to practice &#8220;one assertion per test&#8221; as a strict rule. Instead, it&#8217;s part of my problem-solving strategy when I start to get confused by my own tests; when the tests get so complex that I can&#8217;t quickly understand what&#8217;s going on where. <a class="zem_slink" title="Mock object" rel="wikipedia" href="http://en.wikipedia.org/wiki/Mock_object">Mock objects</a>, in particular, contribute to this, since mock expectations specify what should happen later instead of testing what&#8217;s already happened.</p>
<p>Anyway, when I encounter this problem, known unsurprisingly as Complex Test or <a href="http://xunitpatterns.com/Obscure%20Test.html">Obscure test</a>, my first impulse is to make sure the code I&#8217;m testing (known as the <a class="zem_slink" title="System Under Test" rel="wikipedia" href="http://en.wikipedia.org/wiki/System_Under_Test">system under test</a> or SUT) is not too complex. Classes that are too large and methods that are too long are my prime examples of code that&#8217;s hard to test in a simple way. After I check the SUT, I look at the tests, and yes, then one of my goals is to move toward the &#8220;one assertion&#8221; ideal. It really is helpful at that point.</p>
<p>I&#8217;m open to the possibility that I should be more consistent in applying this principle. He may be right that there is a danger of &#8220;lazy/shallow testing&#8221;. In any case, as with all code, bugs and deficiencies are easier to spot the more readable it is.</p>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Zemified by Zemanta" href="http://reblog.zemanta.com/zemified/6e7736b2-1ac9-453f-9394-9b7870d0e941/"><img class="zemanta-pixie-img" style="border: medium none; float: right;" src="http://img.zemanta.com/reblog_a.png?x-id=6e7736b2-1ac9-453f-9394-9b7870d0e941" alt="Reblog this post [with Zemanta]" /></a></div>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=PHP%20in%20Action&amp;siteurl=http%3A%2F%2Fblog.agilephp.com%2F&amp;linkname=One%20assertion%20per%20test%E2%80%94always%3F&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F02%2F15%2Fone-assertion-per-test%25e2%2580%2594always%2F"><img src="http://blog.agilephp.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://blog.agilephp.com/2009/02/15/one-assertion-per-test%e2%80%94always/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Smart return values</title>
		<link>http://blog.agilephp.com/2009/02/03/return-values/</link>
		<comments>http://blog.agilephp.com/2009/02/03/return-values/#comments</comments>
		<pubDate>Tue, 03 Feb 2009 22:12:46 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[Application design]]></category>
		<category><![CDATA[Clean code]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://blog.agilephp.com/?p=1448</guid>
		<description><![CDATA[



Image by cackhanded via Flickr



Davey Shafik discusses return values from functions. In the specific case of a function that returns values from a database, he wants to return false on error and an empty array if the data set is empty. He also has a reason for that:
“However, it’s very rare that I care about [...]]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img" style="margin: 1em; display: block;">
<div>
<dl class="wp-caption alignleft" style="width: 250px;">
<dt class="wp-caption-dt"><a href="http://www.flickr.com/photos/37354253@N00/74725311"><img title="Return values in JavaScript" src="http://farm1.static.flickr.com/36/74725311_b35c4b1b25_m.jpg" alt="Return values in JavaScript" height="180" width="240"></a></dt>
<dd class="wp-caption-dd zemanta-img-attribution" style="font-size: 0.8em;">Image by <a href="http://www.flickr.com/photos/37354253@N00/74725311">cackhanded</a> via Flickr</dd>
</dl>
</div>
</div>
<p><a href="http://pixelated-dreams.com/archives/479-return-values.html">Davey Shafik</a> discusses return values from functions. In the specific case of a function that returns values from a database, he wants to return false on error and an empty array if the data set is empty. He also has a reason for that:</p>
<p>“However, it’s very rare that I <strong>care</strong> about whether I hit an error condition or just got no result when it comes to display — more to the point, my user doesn’t care.”</p>
<p>That&#8217;s interesting, but I think that someone trying to understand the code might care. It might be easier to read if the two cases were somehow handled separately, at least at the lower levels.</p>
<p>What does help, as pointed out by several commentators, is to throw an exception instead of returning false. The book <a href="http://www.amazon.com/gp/product/0132350882?ie=UTF8&amp;tag=phinac-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0132350882">Clean Code</a> recommends throwing exceptions instead of returning error codes. That gives you flexibility in handling the error. It can be handled at a higher level without having to clutter the levels in-between with error handling code.</p>
<p>In general, it&#8217;s often a good idea to return values that don&#8217;t require any special handling by the calling function. An empty array is an example. Foreach loops will happily do nothing, and everything runs smoothly, although you may need to check for emptiness at some point (typically to give a message such as &#8220;no records found).</p>
<p>Here are some general recommendations for handling return values in PHP. I&#8217;m sure they&#8217;re not perfect, but at least I can enumerate a number of alternatives.</p>
<ul>
<li><strong>Data set</strong>. Return an array (empty if no data is returned). If the data set can be very large, return an SPL iterator that can be used interchangeably with an array in foreach statements. Or, if you have a good reason to do so, return some kind of data set object (<a class="zem_slink" title="Zend Framework" rel="homepage" href="http://framework.zend.com/">Zend Framework</a> does this).</li>
<li><strong>Error condition</strong>.&nbsp; Throw an exception. Or, if it&#8217;s not really an unexpected error, consider letting the calling code test for the error condition before calling the function in question.</li>
<li><strong>Single value</strong>. If you return a data structure as an associative array, it may be useful to return an empty one if nothing is found. Even more interesting is the <a class="zem_slink" title="Null Object pattern" rel="wikipedia" href="http://en.wikipedia.org/wiki/Null_Object_pattern">Null Object pattern</a>. If you would normally return a Contact object and the query returns nothing, return a NullContact object that has null operations and will return false if you call isNull() on it.</li>
</ul>
<p><a href="http://technorati.com/claim/37wzggdh74" rel="me">Technorati Profile</a></p>
<div style="margin-top: 10px; height: 15px;" class="zemanta-pixie"><a class="zemanta-pixie-a" href="http://reblog.zemanta.com/zemified/4399ea86-a66f-42c9-b6d7-188948a0b51b/" title="Zemified by Zemanta"><img style="border: medium none ; float: right;" class="zemanta-pixie-img" src="http://img.zemanta.com/reblog_a.png?x-id=4399ea86-a66f-42c9-b6d7-188948a0b51b" alt="Reblog this post [with Zemanta]"></a></div>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?sitename=PHP%20in%20Action&amp;siteurl=http%3A%2F%2Fblog.agilephp.com%2F&amp;linkname=Smart%20return%20values&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F02%2F03%2Freturn-values%2F"><img src="http://blog.agilephp.com/wp-content/plugins/add-to-any/share_save_256_24.png" width="256" height="24" alt="Share/Save/Bookmark"/></a>

	</p>]]></content:encoded>
			<wfw:commentRss>http://blog.agilephp.com/2009/02/03/return-values/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
