<?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; Application design</title>
	<atom:link href="http://blog.agilephp.com/category/application-design/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>Sounds like an average PHP app to me</title>
		<link>http://blog.agilephp.com/2009/05/04/sounds-like-an-average-php-app-to-me/</link>
		<comments>http://blog.agilephp.com/2009/05/04/sounds-like-an-average-php-app-to-me/#comments</comments>
		<pubDate>Mon, 04 May 2009 18:59:18 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[Application design]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>

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



Image via Wikipedia



Dean Wampler blogs: Is the Supremacy of Object-Oriented Programming Over?
&#8220;The fact is, for a lot of these applications, it’s just data. The ceremony of object wrappers doesn’t carry its weight. Just put the data in a hash map (or a list if you don’t need the bits “labeled”) and then process the collection [...]]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img" style="margin: 1em; display: block;">
<div>
<dl class="wp-caption alignleft" style="width: 164px;">
<dt class="wp-caption-dt"><a href="http://commons.wikipedia.org/wiki/Image:Key_delete.jpg"><img title="Delete key on PC keyboard" src="http://upload.wikimedia.org/wikipedia/commons/2/2c/Key_delete.jpg" alt="Delete key on PC keyboard" width="154" height="164" /></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:Key_delete.jpg">Wikipedia</a></dd>
</dl>
</div>
</div>
<p>Dean Wampler blogs: <a href="http://blog.objectmentor.com/articles/2009/04/20/is-the-supremacy-of-object-oriented-programming-over">Is the Supremacy of Object-Oriented Programming Over?</a></p>
<blockquote><p>&#8220;The fact is, for a lot of these applications, it’s just data. The ceremony of object wrappers doesn’t carry its weight. Just put the data in a hash map (or a list if you don’t need the bits “labeled”) and then process the collection with your iterate, map, and reduce functions. This may sound heretical, but how much Java code could you delete today if you replaced it with a stored procedure?&#8221;</p></blockquote>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><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=Sounds%20like%20an%20average%20PHP%20app%20to%20me&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F05%2F04%2Fsounds-like-an-average-php-app-to-me%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/05/04/sounds-like-an-average-php-app-to-me/feed/</wfw:commentRss>
		<slash:comments>0</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>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>
		<item>
		<title>How code comments deteriorate</title>
		<link>http://blog.agilephp.com/2009/01/04/how-code-comments-deteriorate/</link>
		<comments>http://blog.agilephp.com/2009/01/04/how-code-comments-deteriorate/#comments</comments>
		<pubDate>Sun, 04 Jan 2009 12:24:45 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[Application design]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">http://localhost/wordpress/?p=1403</guid>
		<description><![CDATA[ There was a lot of disagreement on the value of code comments after my earlier post Comments considered harmful. Perhaps the most important objection that was raised was the idea that it&#8217;s OK to improve the code, but it&#8217;s even better to keep the comments in addition to the improved code. 
 As one [...]]]></description>
			<content:encoded><![CDATA[<p> There was a lot of disagreement on the value of code comments after my earlier post <a href="http://www.reiersol.com/blog/1_php_in_action/archive/174_comments_considered_harmful.html">Comments considered harmful</a>. Perhaps the most important objection that was raised was the idea that it&#8217;s OK to improve the code, but it&#8217;s even better to keep the comments in addition to the improved code. </p>
<p> As one of the critics expressed it: </p>
<blockquote><p>   No, comments are there to comment. Period.<br />   That has nothing to do with how good is your code.<br />   You can write perfectly clean code and add good comments to it. Nothing wrong with that. </p></blockquote>
<p> This is one of those ideas that seem obviously true in theory, but fail to work in practice. The reason is that comments get out of sync with the code. The comments rot, or rather, their meaning does. They become more and more misleading as the code gets changed and the comments are not adequately updated.
<p> Let me give you an example. But first, I want to make it clear that I don&#8217;t think code comments are always a bad thing. Sometimes, they are necessary. But much less often than people think. </p>
<p> API documentation is often indispensible, but that&#8217;s really a different matter. When API documentation is generated from comments in front of each method, the primary purpose is to explain how the code can be used, not how it works. In fact, you might say they are code comments only in a syntactical sense. </p>
<p> On to the example. One of the comments to my blog post presented a code snippet that illustrates my point well. It&#8217;s supposed to be a example of a useful inline comment in code. </p>
<pre class="brush: php">
// first handle the case where no records were found
if ($records == 0) {
    return false;
}
</pre>
<p> Is this really an case of good commenting? I don&#8217;t think so.  If it&#8217;s hard to understand that $records == 0 means that no records were found, we can change the code to make it easier.  The simplest way to do it is to rename the variable to something like $numberOfRecordsFound or $numRecordsFound. Or extract a method. But typically, it&#8217;s possible and preferable to avoid this kind of check altogether. </p>
<p> Anyway, the comment is unnecessary. But as I only realized a while later, it&#8217;s also misleading. Does the code &#8220;handle the case where no records were found&#8221;? No, it leaves it to the calling function to handle the case. The one line that returns <tt>false</tt> is not handling anything, it&#8217;s just passing a message. </p>
<p> So the comment is already misleading, never mind what will happen when someone changes the code and neglects to update the comment. For example, let&#8217;s say the next programmer to work on this code is in hurry to fix a bug. Now maybe the code will look like this: </p>
<pre class="brush: php">
// first handle the case where no records were found
if ($records == 0 &amp;&amp; $state == ACTIVE) {
    return false;
}
</pre>
<p> The programmer wonders briefly whether the comment is still fully appropriate, is unsure, and decides to do nothing about it (or postpones the decision and forgets about it). Now, perhaps (we can&#8217;t quite tell without the full context), the comment is even more misleading.  </p>
<p> In the next round, yet another programmer comes along, makes some more code changes and wonders: &#8220;Should I update the comment? It looks all wrong to me, but it was probably written by someone with deeper insignt into the code. Better leave it alone.&#8221; </p>
<p> The code would have been better off without the comment, but no one wants to delete it, especially since they have been told that comments are so important. It&#8217;s a downward spiral: the code changes make the comments misleading less chance that they will  </p>
<p> Comments that lie are worse than no comments, and in practice they tend to big liars. </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=How%20code%20comments%20deteriorate&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F01%2F04%2Fhow-code-comments-deteriorate%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/01/04/how-code-comments-deteriorate/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Comments considered harmful</title>
		<link>http://blog.agilephp.com/2008/12/23/comments-considered-harmful/</link>
		<comments>http://blog.agilephp.com/2008/12/23/comments-considered-harmful/#comments</comments>
		<pubDate>Tue, 23 Dec 2008 20:11:54 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[Application design]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://localhost/wordpress/?p=1383</guid>
		<description><![CDATA[There is too much old advice in PHP. A recent case comes from the PHP     Advent calendar. Eli       White is a strong believer in commenting code, including inline     comments inside functions.
Unfortunately, he&#8217;s at least 10 years too late. This used to [...]]]></description>
			<content:encoded><![CDATA[<p>There is too much old advice in PHP. A recent case comes from the PHP     Advent calendar. <a href="http://phpadvent.org/2008/commenting-on-comments-by-eli-white">Eli       White</a> is a strong believer in commenting code, including inline     comments inside functions.</p>
<p>Unfortunately, he&#8217;s at least 10 years too late. This used to be good advice, but not any more.</p>
<p>Up to a point, he&#8217;s right. Making code as easy to understand as possible is     essential and can save a huge amount of time later. And adding comments to     unreadable code is better than leaving it the way it is.</p>
<p>There is a better way, though. <a class="zem_slink" title="Code refactoring" rel="wikipedia" href="http://en.wikipedia.org/wiki/Code_refactoring">Refactor</a> your code so it&#8217;s easy to     understand even without comments. I&#8217;m just reading <a class="zem_slink" title="Robert Cecil Martin" rel="wikipedia" href="http://en.wikipedia.org/wiki/Robert_Cecil_Martin">Robert C. Martin</a>&#8217;s     recent book <em>Clean Code</em>.  He is very clear on this point.</p>
<blockquote><p>Clear and expressive code with few comments is far superior to cluttered       and complex code with lots of comments. Rather than spend your time       writing the comments that explain the mess you made, spend it cleaning       that mess.</p></blockquote>
<p>The principle is simple: if you have an inline comment in a method (or     function), take the chunk of code that the comment refers to and extract it     into a separate method. Give the method an intention-revealing       name. Typically, you won&#8217;t need the comment afterwards.</p>
<p>I&#8217;m sure we need an example. Here&#8217;s a small excerpt from a method taken from <a class="zem_slink" title="Zend Framework" rel="homepage" href="http://framework.zend.com/">Zend Framework</a>.</p>
<pre class="brush: php">
protected function _doUpdate()
{
...
        /**
         * Execute cascading updates against dependent tables.
         * Do this only if primary key value(s) were changed.
         */
        if (count($pkDiffData) &gt; 0) {
            $depTables = $this-&gt;_getTable()-&gt;getDependentTables();
            if (!empty($depTables)) {
                $db = $this-&gt;_getTable()-&gt;getAdapter();
                $pkNew = $this-&gt;_getPrimaryKey(true);
                $pkOld = $this-&gt;_getPrimaryKey(false);
                foreach ($depTables as $tableClass) {
                    try {
                        @Zend_Loader::loadClass($tableClass);
                    } catch (Zend_Exception $e) {
                        require_once &#039;Zend/Db/Table/Row/Exception.php&#039;;
                        throw new Zend_Db_Table_Row_Exception($e-&gt;getMessage());
                    }
                    $t = new $tableClass(array(&#039;db&#039; =&gt; $db));
                    $t-&gt;_cascadeUpdate($this-&gt;getTableClass(), $pkOld, $pkNew);
                }
            }
        }
</pre>
<p>By changing some temporary varibles into instance variables and extracting a couple of methods,    we can get code like this:</p>
<pre class="brush: php">
if ($this-&gt;primaryKeyValuesHaveChanged() {
    $this-&gt;executeCascadingUpdatesOnDependentTables();
}
</pre>
<p>Or even, by extracting a couple of classes, making objects out of two of the concepts involved, we might end up with something like this.</p>
<pre class="brush: php">
if ($primaryKeys-&gt;valuesHaveChanged() {
     $dependentTables-&gt;executeCascadingUpdates();
}
</pre>
<p>This uses most of the words from the original comment, but it&#8217;s superior for   several reasons. First and foremost, the section of code as a whole is clearer.   Second, comments have a tendency to get out of sync with the code. By   expressing the message in the code itself instead, we can avoid that.   Third, the extraction itself has the positive side-effect of making it possible   to test the extracted method in isolation.</p>
<p>Improving the code itself is harder than writing comments, but it&#8217;s worth it. .</p>
<div style="margin-top: 10px; height: 15px;" class="zemanta-pixie"><a class="zemanta-pixie-a" href="http://reblog.zemanta.com/zemified/61cc5cf5-e2d2-47e1-aca9-1e47fc0ad1bc/" title="Reblog this post [with Zemanta]"><img style="border: medium none ; float: right;" class="zemanta-pixie-img" src="http://img.zemanta.com/reblog_a.png?x-id=61cc5cf5-e2d2-47e1-aca9-1e47fc0ad1bc" alt="Reblog this post [with Zemanta]"></a><span class="zem-script more-related pretty-attribution"><script type="text/javascript" src="http://static.zemanta.com/readside/loader.js" defer="defer"></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=Comments%20considered%20harmful&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2008%2F12%2F23%2Fcomments-considered-harmful%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/2008/12/23/comments-considered-harmful/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>The one-line web framework</title>
		<link>http://blog.agilephp.com/2008/12/14/the-one-line-web-framework/</link>
		<comments>http://blog.agilephp.com/2008/12/14/the-one-line-web-framework/#comments</comments>
		<pubDate>Sun, 14 Dec 2008 14:53:49 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[Application design]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://localhost/wordpress/?p=1386</guid>
		<description><![CDATA[ The core of your average web framework is a Front Controller. Front Controllers are commonly considered complex and esoteric.  That&#8217;s a myth. I sometimes brag that I can construct a Front Controller in 15 minutes. Actually, it&#8217;s doesn&#8217;t take quite that long. In PHP, a Front Controller can be simplified to just one [...]]]></description>
			<content:encoded><![CDATA[<p> The core of your average web framework is a Front Controller. Front Controllers are commonly considered complex and esoteric.  That&#8217;s a myth. I sometimes brag that I can construct a Front Controller in 15 minutes. Actually, it&#8217;s doesn&#8217;t take quite that long. In PHP, a Front Controller can be simplified to just one line of code: </p>
<pre class="brush: php">
call_user_func($_REQUEST[&#039;action&#039;]);
</pre>
<p> <b>Warning: Do not use this in a real application.</b> </p>
<p> There is one and only one good reason why you shouldn&#8217;t: it&#8217;s totally insecure. Except for that, it&#8217;s simple but perfectly viable. Your actions will be just plain functions, which is pretty simplistic and will be hard to handle if you build many of them. But it&#8217;s a huge improvement over the average PHP script with no systematic handling of the PHP request. </p>
<p> If you want to do something more like the frameworks such as Zend Framework, you want your actions as methods grouped into classes (called Controllers in ZF). </p>
<p> Now you need two lines. The following script demonstrates this: </p>
<pre class="brush: php">
// Pretend we have an HTTP request
$_REQUEST = array(&#039;controller&#039; =&gt; &#039;Contacts&#039;, &#039;action&#039; =&gt; &#039;edit&#039;);

// Front controller
$controller = new $_REQUEST[&#039;controller&#039;];
call_user_func(array($controller,$_REQUEST[&#039;action&#039;]));

// The action controller class
class Contacts {
    function edit() {
        echo \&quot;ok\n\&quot;;
    }
}
</pre>
<p> You can start with something like it (assuming that security has been taken care of) and add features as you need them. </p>
<p> In case you&#8217;re wondering how to what exactly the security issues are, the most obvious problem is the fact that any user can run any method in any class that is available to this script. The way to avoid that append or prepend some fixed string to the class and the method name. For instance, in Zend Framework, the action name edit will activate the method editAction(). </p>
<p> Beyond that, the security problems are the usual ones. You need to <a href="http://shiflett.org/articles/input-filtering">filter input</a>, And in general you should beware of $_REQUEST, since it can also contain cookie data. </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=The%20one-line%20web%20framework&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2008%2F12%2F14%2Fthe-one-line-web-framework%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/2008/12/14/the-one-line-web-framework/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>How to test everything</title>
		<link>http://blog.agilephp.com/2008/11/27/how-to-test-everything/</link>
		<comments>http://blog.agilephp.com/2008/11/27/how-to-test-everything/#comments</comments>
		<pubDate>Thu, 27 Nov 2008 23:19:04 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[Application design]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://localhost/wordpress/?p=1389</guid>
		<description><![CDATA[They say there&#8217;s no free lunch, but at least there&#8217;s free breakfast. Last week I attended a &#8220;breakfast seminar&#8221; with Robert C. Martin (Uncle Bob). There really was free food.
Anyway, Uncle Bob held an extremely entertaining and useful introduction to the FitNesse testing tool. He got me hooked on it, but I&#8217;m even more fascinated [...]]]></description>
			<content:encoded><![CDATA[<p>They say there&#8217;s no free lunch, but at least there&#8217;s free breakfast. Last week I attended a &#8220;breakfast seminar&#8221; with Robert C. Martin (Uncle Bob). There really was free food.</p>
<p>Anyway, Uncle Bob held an extremely entertaining and useful introduction to the <a href="http://fitnesse.org/">FitNesse</a> testing tool. He got me hooked on it, but I&#8217;m even more fascinated by something else. I asked him, &#8220;what is the nature of the test API [you've been talking about]?&#8221; He answered that question, and also another, more general one: What is a good strategy for complete automated integration and acceptance testing of an application? That was the question I really wanted to ask, only I wasn&#8217;t quite aware that I wanted to ask it. And, impressively, he answered it anyway.</p>
<p>As I understood it, the strategy he outlined was as follows. The diagram is probably only a mild perversion of the one he drew on the whiteboard.</p>
<p><img class="alignnone size-full wp-image-1442" title="totaltest" src="http://blog.agilephp.com/wp-content/uploads/2008/11/totaltest.jpg" alt="totaltest" width="510" height="370" /></p>
<ul>
<li>Test all features through a test API just underneath the user   inteface. These are the main acceptance tests; the ones that are used to   decide whether a feature is <strong>done</strong> or not done yet.</li>
<li>Test the user interface in isolation, running calls to a fake system underneath.</li>
<li>Run just a <em>few</em> tests all the way through the application to   test the plumbing between the user interface and the rest of the   system.</li>
</ul>
<p>The reason why we don&#8217;t want all our acceptance tests to go through the user interface is that the user interface has a tendency to change often, and changes in the user interface tend to breaks lots of tests.</p>
<p>This resonates reasonably well with my experience, although I think testing &#8220;everything&#8221; through the user interface can work sometimes, if the user interface is a very plain one.</p>
<p>In addition, we want unit tests for each small piece of the application. The tests outlined above are just catch the few bugs that are not detected by the unit tests.</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=How%20to%20test%20everything&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2008%2F11%2F27%2Fhow-to-test-everything%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/2008/11/27/how-to-test-everything/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>More beautiful code</title>
		<link>http://blog.agilephp.com/2008/11/08/more-beautiful-code/</link>
		<comments>http://blog.agilephp.com/2008/11/08/more-beautiful-code/#comments</comments>
		<pubDate>Sat, 08 Nov 2008 05:34:42 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[Application design]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://localhost/wordpress/?p=1395</guid>
		<description><![CDATA[ I got some interesting comments to my previous post on &#8220;beautiful code&#8221;. Some were pretty strong disagreements. 
 So am I wrong? Did I get carried away? Did my critical faculty go on vacation somewhere nice and sunny? I admit that sometimes I deliberately look at the positive and ignore the negative. (And sometimes [...]]]></description>
			<content:encoded><![CDATA[<p> I got some interesting comments to my previous post on <a href="http://www.reiersol.com/blog/1_php_in_action/archive/168_beautiful_code.html">&#8220;beautiful code&#8221;</a>. Some were pretty strong disagreements. </p>
<p> So am I wrong? Did I get carried away? Did my critical faculty go on vacation somewhere nice and sunny? I admit that sometimes I deliberately look at the positive and ignore the negative. (And sometimes I do the opposite; It&#8217;s a good exercise if you&#8217;re careful.) </p>
<p> I wasn&#8217;t drunk, anyway. But let me take a closer look at the particular line of code I was praising: </p>
<pre class="brush: php">
$this-&gt;assertThat($form-&gt;hasSelect(withName(&#039;statusConfirm&#039;))-&gt;hasValues(),
    array(&#039;Yes&#039;,&#039;No&#039;));
</pre>
<p> My main point is that it&#8217;s close to plain English. Not everyone agrees that that&#8217;s a good thing, but I argue that we&#8217;re built (genetically wired, in fact) to understand natural languages, not program code. Therefore code should be easier to understand when it approximates natural language and expression. And we&#8217;re trying to create or approximate a Domain Specific Language (DSL), which should express exactly what&#8217;s required for the domain and not the demands of the technical implementation. </p>
<p> So for this experiment, let&#8217;s translate this one into a (plain English sentence: </p>
<p> Assert that Form (this particular one) has a select menu with the name &#8220;statusConfirm&#8221; and values &#8220;yes&#8221; and &#8220;no&#8221; </p>
<p> Translating back into code, it might look more like this: </p>
<pre class="brush: php">
$this-&gt;assertThat($form)-&gt;hasSelect()-&gt;withName(&#039;statusConfirm&#039;)-&gt;andValues(&#039;yes&#039;,&#039;no&#039;);
</pre>
<p> To me, this is even more natural than the other one. I think we&#8217;ve gotten rid of some syntax that has to do with implementation details rather than making the API simple to use. </p>
<p> It also seems clear to me how this could be implemented. All of the method calls could be to an assertion object that would take all these various inputs and always return itself at the end of the method so you can chain the calls in what&#8217;s known as a fluent interface. </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=More%20beautiful%20code&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2008%2F11%2F08%2Fmore-beautiful-code%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/2008/11/08/more-beautiful-code/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Beautiful code</title>
		<link>http://blog.agilephp.com/2008/11/03/beautiful-code/</link>
		<comments>http://blog.agilephp.com/2008/11/03/beautiful-code/#comments</comments>
		<pubDate>Mon, 03 Nov 2008 13:36:56 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[Application design]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://localhost/wordpress/?p=1398</guid>
		<description><![CDATA[     Max Horwath has published his slides on Making       Selenium Test Writing easier using a DSL onlinefrom IPC 2008. Let me     quote the whole short description:     
 Implementing automated tests by using Seleniums API methods has several [...]]]></description>
			<content:encoded><![CDATA[<p>     Max Horwath has published his slides on <a href="http://www.maxhorvath.com/2008/10/slide-for-ipc-session-on-making-selenium-test-writing-easier-using-a-dsl-online.html">Making       Selenium Test Writing easier using a DSL online</a>from <a href="http://it-republik.de/php/phpconference/">IPC 2008</a>. Let me     quote the whole short description:     </p>
<blockquote><p> Implementing automated tests by using Seleniums API methods has several drawbacks. Selenium is great for what it does, providing a generic framework for testing a generic application. Using the Testing_SeleniumDSL framework, I will show you how to create your own Domain Specific Language (DSL), which would allow you to write tests in the language of your business rather than in Seleniums language.  </p></blockquote>
<p> I&#8217;m quite impressed by the examples he presents, such as: </p>
<pre class="brush: php">
$this-&gt;assertThat($form-&gt;hasSelect(withName(&#039;statusConfirm&#039;))-&gt;hasValues(),
    array(&#039;Yes&#039;,&#039;No&#039;));
</pre>
<p> This is truly expressive, readable code. I&#8217;ve refactored web test code in this direction many times, but I admit I  never got quite this far. </p>
<p>  The DSL is planned as an open source release. It would be interesting to try something  similar for the SimpleTest web tester, which is my favorite for testing web interfaces without too much JavaScript. (Based on <a href="http://www.reiersol.com/blog/1_php_in_action/archive/25_paparrazzi_testing.html">the paparrazzi principle</a>.) </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=Beautiful%20code&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2008%2F11%2F03%2Fbeautiful-code%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/2008/11/03/beautiful-code/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>
