<?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; PHP</title>
	<atom:link href="http://blog.agilephp.com/tag/php/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>Real programming with PHP 5.3 (part 4): A more realistic example</title>
		<link>http://blog.agilephp.com/2009/06/02/real-programming-with-php-53-part-4-a-more-realistic-example/</link>
		<comments>http://blog.agilephp.com/2009/06/02/real-programming-with-php-53-part-4-a-more-realistic-example/#comments</comments>
		<pubDate>Tue, 02 Jun 2009 21:12:54 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[JavaScript/Ajax]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[PHP 5.3]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Object-Oriented]]></category>

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



Image by hartboy via Flickr



My previous example in part 2 was just &#8220;hello world&#8221;, so I&#8217;m going to try for something more like the real world. You may find this example unusual, but it does work. I took the PageRange class I used in my July 2007 php&#124;architect article and converted it to the JavaScript [...]]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img" style="margin: 1em; display: block;">
<div>
<dl class="wp-caption alignleft">
<dt class="wp-caption-dt"><a href="http://www.flickr.com/photos/26013750@N00/2801578749"><img src="http://farm4.static.flickr.com/3162/2801578749_4768ccc57f_m.jpg" alt="Let's be realistic" title="Let's be realistic"></a></dt>
<dd class="wp-caption-dd zemanta-img-attribution" style="font-size: 0.8em;">Image by <a href="http://www.flickr.com/photos/26013750@N00/2801578749">hartboy</a> via Flickr</dd>
</dl>
</div>
</div>
<p>My previous example in <a href="http://blog.agilephp.com/2009/03/31/real-programming-with-php-53-part-2-javascript-style-classes/">part 2</a> was just &#8220;hello world&#8221;, so I&#8217;m going to try for something more like the real world. You may find this example unusual, but it does work. I took the PageRange class I used in my <a href="http://phparch.com/c/magazine/issue/56">July 2007 php|architect</a> article and converted it to the JavaScript style. The class is a variation on Martin Fowler&#8217;s Range pattern, and is the hub of a re-implementation of the main functionality of PEAR Pager, using a more object-oriented style.</p>
<p>A Range object is defined by just two values (three in my variation), so it might seem like too much to have an object just to keep these values, but as you can see from the example, a Range class can have behaviors to change and compare ranges.</p>
<p>As before, I&#8217;m defining most of the methods inside the constructor.</p>
<pre class="brush: php">
&lt;?php
class PageRange {
    public $start;
    public $end;
    public $length;

    private $moveToStartAt;
    private $moveToEndAt;
    private $changeLengthToEndAt;
    private $includes;
    private $isInside;
    private $extendsBeyondStartOf;
    private $extendsBeyondEndOf;
    private $truncateToFitInside;
    private $moveToFitInside;
    private $asArray;

    public function __construct($start,$end,$length) {
        $self = $this;
        $this-&gt;start = $start;
        $this-&gt;end = $end;
        $this-&gt;length = $length;

        $this-&gt;moveToStartAt = function($start) use ($self) {
            return PageRange::withStartAndLength(
                $start,$self-&gt;length);
        };

        $this-&gt;moveToEndAt = function($end) use ($self) {
            return PageRange::withEndAndLength($end,$self-&gt;length);
        };

        $this-&gt;changeLengthToEndAt = function($end) use ($self) {
            return PageRange::withStartAndEnd($self-&gt;start,$end);
        };

        // Comparisons

        $this-&gt;includes = function($page) use ($self) {
            return $page &gt;= $self-&gt;start
                &amp;&amp; $page &lt;= $self-&gt;end;
        };

        $this-&gt;isInside = function($range) use ($self) {
            return $range-&gt;includes($self-&gt;getStart())
                &amp;&amp; $range-&gt;includes($self-&gt;getEnd());
        };

        $this-&gt;extendsBeyondStartOf = function(PageRange $range) use ($self) {
            return ($self-&gt;getStart() &lt; $range-&gt;getStart());
        };

        $this-&gt;extendsBeyondEndOf = function(PageRange $range) use ($self) {
            return ($self-&gt;getEnd() &gt; $range-&gt;getEnd());
        };

        // Changes

        $this-&gt;truncateToFitInside = function(PageRange $larger) use ($self) {
            if ($self-&gt;isInside($larger)) return clone $self;
            return $self-&gt;changeLengthToEndAt(
                $larger-&gt;getEnd());
        };

        $this-&gt;moveToFitInside = function(PageRange $larger) use ($self) {
            if ($self-&gt;isInside($larger)) return clone $self;
            if ($self-&gt;extendsBeyondEndOf($larger))
                return $self-&gt;moveToEndAt($larger-&gt;getEnd());
            if ($self-&gt;extendsBeyondStartOf($larger))
                return $self-&gt;moveToStartAt(
                    $larger-&gt;getStart());
        };

        // Convert to array

        $this-&gt;asArray = function() use ($self) {
            return range($self-&gt;start,$self-&gt;end);
        };

    }
</pre>
<p>I&#8217;ve defined the static methods in the usual way, non-JavaScript style. And there is, of course, the mandatory __call() method.</p>
<pre class="brush: php">
class PageRange...

    public function __call($method,$args) {
        return call_user_func_array($this-&gt;$method,$args);
    }

    public function getStart() { return $this-&gt;start; }

    public function getEnd() { return $this-&gt;end; }

    public function getLength() { return $this-&gt;length; }

    private static function calculateEnd($start,$length) {
        return $start + $length - 1;
    }

    private static function calculateStart($end,$length) {
        return $end - $length + 1;
    }

    private static function calculateLength($start,$end) {
        return $end - $start + 1;
    }

    public static function withStartAndLength(
        $start,$length)
    {
        return new self(
            $start,
            self::calculateEnd($start,$length),
            $length
        );
    }

    public static function withEndAndLength($end,$length) {
        return new self(
            self::calculateStart($end,$length),
            $end,
            $length
        );
    }

    public static function withStartAndEnd($start,$end) {
        return new self(
            $start,
            $end,
            self::calculateLength($start,$end)
        );
    }

}
</pre>
<p>An interesting aspect of this class is the fact that the constructor is private, so you have to use one of the creation methods. That&#8217;s part of my variation on the range pattern.</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%204%29%3A%20A%20more%20realistic%20example&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F06%2F02%2Freal-programming-with-php-53-part-4-a-more-realistic-example%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/06/02/real-programming-with-php-53-part-4-a-more-realistic-example/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Show me your code comments and I&#8217;ll show why you don&#8217;t need them</title>
		<link>http://blog.agilephp.com/2009/04/30/show-me-your-code-comments-and-ill-show-why-you-dont-need-them/</link>
		<comments>http://blog.agilephp.com/2009/04/30/show-me-your-code-comments-and-ill-show-why-you-dont-need-them/#comments</comments>
		<pubDate>Thu, 30 Apr 2009 20:52:45 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Martin Fowler]]></category>
		<category><![CDATA[Technical debt]]></category>
		<category><![CDATA[Ward Cunningham]]></category>

		<guid isPermaLink="false">http://blog.agilephp.com/?p=1567</guid>
		<description><![CDATA[Brandon Savage has written a blog post On Code Commenting And Technical Debt. He believes that code comments are a good way to minimize technical debt.

I&#8217;m surprised to find the term technical debt mentioned without being accompanied by the term refactoring. Refactoring is generally recognized (outside the PHP world) as the way to pay down [...]]]></description>
			<content:encoded><![CDATA[<p>Brandon Savage has written a blog post <a href="http://www.brandonsavage.net/on-code-commenting-and-technical-debt/">On Code Commenting And Technical Debt</a>. He believes that code comments are a good way to minimize <a class="zem_slink" title="Technical debt" rel="wikipedia" href="http://en.wikipedia.org/wiki/Technical_debt">technical debt</a>.<br />
<a href="http://www.brandonsavage.net/on-code-commenting-and-technical-debt/"></a><br />
I&#8217;m surprised to find the term technical debt mentioned without being accompanied by the term <a class="zem_slink" title="Code refactoring" rel="wikipedia" href="http://en.wikipedia.org/wiki/Code_refactoring">refactoring</a>. Refactoring is generally recognized (outside the PHP world) as <em>the</em> way to pay down technical debt. Commenting may help, but is clearly the second-best practice.</p>
<p><a href="http://martinfowler.com/bliki/TechnicalDebt.html">Martin Fowler</a> puts it this way:</p>
<blockquote><p>Technical Debt is a wonderful metaphor developed by <a class="zem_slink" title="Ward Cunningham" rel="wikipedia" href="http://en.wikipedia.org/wiki/Ward_Cunningham">Ward Cunningham</a> to help us think about this problem. In this metaphor, doing things the quick and dirty way sets us up with a technical debt, which is similar to a financial debt. Like a financial debt, the technical debt incurs interest payments, which come in the form of the extra effort that we have to do in future development because of the quick and dirty design choice. We can choose to continue paying the interest, or we can pay down the principal by refactoring the quick and dirty design into the better design. Although it costs to pay down the principal, we gain by reduced interest payments in the future.</p></blockquote>
<p>Brandon&#8217;s argument in favor of commenting is perfectly valid, but misses the crux of the matter, since he ignores the option of actually improving the code itself rather than just adding comments.</p>
<p>Let me also comment briefly on <a href="http://mtabini.blogspot.com/2009/04/myth-of-myth-of-self-commenting-code.html">Marco Tabini&#8217;s reponse</a>:</p>
<blockquote><p>What I suspect Brandon really means is that the comments are there to illustrate the intentions of the author <span style="font-style: italic;">when those intentions are not immediately made obvious by the code itself</span>.</p></blockquote>
<p>Yes. And no. There is no absolute boundary, no limit in principle, to how <a href="http://c2.com/cgi/wiki/wiki?IntentionRevealingNames">intention-revealing</a> code can be. It&#8217;s not necessarily easy in practice, though. As I&#8217;ve said before, it&#8217;s primarily inline comments that I&#8217;m objecting to. The comments I feel a need to write are often at the class level and address the interaction between different classes.</p>
<p>Anyway, arguing about it theoretically is not the way to resolve the issue. Show me some good examples of comments that serve to make code clearer and that supposedly can&#8217;t be usefully eliminated by refactoring the code into something more readable. I&#8217;ll either admit that you&#8217;re right or show you (or at least outline) how to do it differently. I do recognize that even inline comments are useful&#8230;<em>occasionally</em>.<a href="http://mtabini.blogspot.com/2009/04/myth-of-myth-of-self-commenting-code.html"></a></p>
<p>(By the way, I seem to have missed Brandon&#8217;s comment (<a href="http://www.brandonsavage.net/where-comments-are-useful/">Where Comments Are Useful</a>) to my <a href="http://blog.agilephp.com/2008/12/23/comments-considered-harmful/">comments considered harmful</a> post last December.)</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=Show%20me%20your%20code%20comments%20and%20I%26%238217%3Bll%20show%20why%20you%20don%26%238217%3Bt%20need%20them&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F04%2F30%2Fshow-me-your-code-comments-and-ill-show-why-you-dont-need-them%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/30/show-me-your-code-comments-and-ill-show-why-you-dont-need-them/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>10 ways to improve your code</title>
		<link>http://blog.agilephp.com/2009/04/21/10-ways-to-improve-your-code/</link>
		<comments>http://blog.agilephp.com/2009/04/21/10-ways-to-improve-your-code/#comments</comments>
		<pubDate>Tue, 21 Apr 2009 13:55:44 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Neal Ford]]></category>

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



Image by Jared Richardson via Flickr



I discovered a video presentation available from QCon SF 2008 by Neal Ford called 10 Ways to Improve Your Code. Although the examples are in Java, most of the presentation is relevant to PHP. There are some ideas here that I&#8217;ve never heard of myself, such as &#8220;anti-objects&#8221;.
Some of the [...]]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img" style="margin: 1em; display: block;">
<div>
<dl class="wp-caption alignright" style="width: 250px;">
<dt class="wp-caption-dt"><a href="http://www.flickr.com/photos/38701974@N00/3296805817"><img title="Neal's Drink of Choice" src="http://farm4.static.flickr.com/3408/3296805817_651ae870f2_m.jpg" alt="Neal's Drink of Choice" width="240" height="160" /></a></dt>
<dd class="wp-caption-dd zemanta-img-attribution" style="font-size: 0.8em;">Image by <a href="http://www.flickr.com/photos/38701974@N00/3296805817">Jared Richardson</a> via Flickr</dd>
</dl>
</div>
</div>
<p>I discovered a video presentation available from QCon SF 2008 by Neal Ford called <a href="http://www.infoq.com/presentations/10-Ways-to-Better-Code-Neal-Ford">10 Ways to Improve Your Code</a>. Although the examples are in Java, most of the presentation is relevant to PHP. There are some ideas here that I&#8217;ve never heard of myself, such as &#8220;anti-objects&#8221;.</p>
<p>Some of the main headings are a bit cryptic, so you may have to see the video itself to have them explained.</p>
<p>Here are the 10 ways:</p>
<ol>
<li>Composed method</li>
<li>TDD (test-driven development/design)</li>
<li>Static analysis</li>
<li>Good citizenship</li>
<li>YAGNI (you ain&#8217;t gonna need it)</li>
<li>Question authority</li>
<li>SLAP (single level of abstraction principle)</li>
<li>Polyglot programming</li>
<li>Every nuance (=learn every nuance of your programming language)</li>
<li>Anti-objects</li>
</ol>
<p>I recommend this presentation. It&#8217;s about the things that really matter if you want to be productive.</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/62d5831b-11bf-4961-b232-771ffbf9ca7e/"><img class="zemanta-pixie-img" style="border: medium none; float: right;" src="http://img.zemanta.com/reblog_a.png?x-id=62d5831b-11bf-4961-b232-771ffbf9ca7e" 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=10%20ways%20to%20improve%20your%20code&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F04%2F21%2F10-ways-to-improve-your-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/2009/04/21/10-ways-to-improve-your-code/feed/</wfw:commentRss>
		<slash:comments>5</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>Real programming with PHP 5.3 (part 2): JavaScript-style classes</title>
		<link>http://blog.agilephp.com/2009/03/31/real-programming-with-php-53-part-2-javascript-style-classes/</link>
		<comments>http://blog.agilephp.com/2009/03/31/real-programming-with-php-53-part-2-javascript-style-classes/#comments</comments>
		<pubDate>Tue, 31 Mar 2009 11:45:10 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[PHP 5.3]]></category>
		<category><![CDATA[Hello world program]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://blog.agilephp.com/?p=1535</guid>
		<description><![CDATA[
In part one of this series, we looked at the ability to use lambda functions or closures to process arrays. In this part, we will see how closures can be used to build classes in a completely new way.


After I did my own research, I discovered that someone had beat me to it. As early [...]]]></description>
			<content:encoded><![CDATA[<p>
In <a href="http://blog.agilephp.com/2009/03/19/real-programming-with-php-53-part-1-array-processing/">part one of this series</a>, we looked at the ability to use lambda functions or closures to process arrays. In this part, we will see how closures can be used to build classes in a completely new way.
</p>
<p>
After I did my own research, I discovered that someone had beat me to it. As early as September last year Fredrik Holmström wrote about <a href="http://loveandtheft.org/2008/09/20/javascript-oo-python-ducktyping-in-php53/">Javascript-OO &#038; Python-DuckTyping in PHP5.3</a>.
</p>
<p>
I&#8217;ve done the same thing independently and somewhat differently, so it&#8217;s interesting to compare. Unlike Holmström, I&#8217;m defining the closures inside the constructor for the class that&#8217;s using them. That makes the code that uses the class a little more similar to what we&#8217;re used to.
</p>
<p>
Let&#8217;s start with a &#8220;Hello world&#8221; example.
</p>
<pre class="brush: php">
class HelloWorldWithClosures {
    private $hello;
    private $goodbye;

    public function __construct() {
        // If we try using $this inside the closure, we get a syntax error.
        // So we need another variable name, which is basically arbitrary.
        $self = $this;

        // $self is not actually used inside this method/closure, but we want to be consistent.
        $this-&gt;hello = function() use ($self) {
            echo &quot;hello world...\n&quot;;
        };

        $this-&gt;goodbye = function() use ($self) {
            $self-&gt;hello();
            echo &quot;...and goodbye for now\n&quot;;
        };
    }

    public function __call($method,$args) {
        return call_user_func_array($this-&gt;$method,$args);
    }
}
</pre>
<p>
The closures are instance variables in the class, and the __call() method is set up to call the correct closure when calling the method in the usual way in PHP.
</p>
<p>
Now we can call a plain method that uses nothing else from the class:
</p>
<pre class="brush: php">
$obj = new HelloWorldWithClosures;
$obj-&gt;hello(); // prints &quot;hello world...&quot;
</pre>
<p>And we can call the goodbye() method that starts by calling hello():</p>
<pre class="brush: php">
$obj = new HelloWorldWithClosures;
$obj-&gt;goodbye();
// prints &quot;hello world...
//...and goodbye for now&quot;
</pre>
<p>We can also add new methods to object that&#8217;s already instantiated without changing the class:</p>
<pre class="brush: php">
$obj-&gt;helloAgain = function() use($obj) {
    $obj-&gt;goodbye();
    echo &quot;...and hello again\n&quot;;
};
</pre>
<p>
This last example exploits the somewhat vulgar fact that you can still add public instance variables on the fly to an object, as in PHP 4.
</p>
<p>
A different approach that avoids this, but is a bit more verbose, would be to use an array to store the closures in the object:
</p>
<pre class="brush: php">
class HelloWorldWithClosures2 {
    public $methods = array();

    public function __construct() {
        $self = $this;

        $this-&gt;methods[&#039;hello&#039;] = function() use ($self) {
            echo &quot;hello world...\n&quot;;
        };

        $this-&gt;methods[&#039;goodbye&#039;] = function() use ($self) {
            $self-&gt;hello();
            echo &quot;...and goodbye for now\n&quot;;
        };
    }

    public function __call($method,$args) {
        return call_user_func_array($this-&gt;methods[$method],$args);
    }
}
</pre>
<p>
In addition, we would normally need to throw an execption when a method does not exist. The blog post I linked to at the beginning has this feature.
</p>
<p>
Those are the basics of how to write JavaScript-classes in PHP 5.3. Whether you actually want do it this way depends on your needs.  There&#8217;s no point unless you actually want to use the flexibility this style of programmer affords.</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%202%29%3A%20JavaScript-style%20classes&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F03%2F31%2Freal-programming-with-php-53-part-2-javascript-style-classes%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/03/31/real-programming-with-php-53-part-2-javascript-style-classes/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Real programming with PHP 5.3 (part 1): array processing</title>
		<link>http://blog.agilephp.com/2009/03/19/real-programming-with-php-53-part-1-array-processing/</link>
		<comments>http://blog.agilephp.com/2009/03/19/real-programming-with-php-53-part-1-array-processing/#comments</comments>
		<pubDate>Thu, 19 Mar 2009 09:48:33 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://blog.agilephp.com/?p=1513</guid>
		<description><![CDATA[You may have heard of the new features that are scheduled for PHP 5.3, but who knows what they can be used for in real programming? I took the time for some experimental research, and came up with a few examples.
At the PHP UK conference, I saw Sebastian Bergmann&#8217;s presentation on lambda functions, closures and [...]]]></description>
			<content:encoded><![CDATA[<p>You may have heard of the new features that are scheduled for PHP 5.3, but who knows what they can be used for in real programming? I took the time for some experimental research, and came up with a few examples.</p>
<p>At the PHP UK conference, I saw <a href="http://www.slideshare.net/sebastian_bergmann/of-lambda-functions-closures-and-traits">Sebastian Bergmann&#8217;s presentation on lambda functions, closures and traits</a>. Lambda functions and closures are scheduled for 5.3  (or fivethree, as I&#8217;ve affectionately named the binary), or later. The presentation was intriguing, but has only simplistic examples, sufficient to illustrate the mechanical aspects. It left me curious as to what these features could be used for in real programs.</p>
<p>Before we start playing, let&#8217;s get the basic terminology clear. Lambda functions and closures are two fancy names for (variations on) anonymous functions. These are functions that are more flexible than ordinary functions and can be stored in variables or defined just where they are needed.</p>
<p>Anonymous functions are possible even in pre-5.3 PHP. They can be created using <code>create_function()</code>. But this is cumbersome, ugly, error-prone and possibly insecure. PHP 5.3 lets you do this in a much more natural and pleasant way.</p>
<p>The most basic and obvious case is sorting. Here is an example from Sebastian&#8217;s presentation:</p>
<pre class="brush: php">

&lt;?php

usort(
    $list,
    function ($a, $b) {
        if ($a == $b) return 0;
        return ($a &lt; $b) ? -1 : 1;
    }
);
</pre>
<p>In PHP before 5.3, this must be done either by using <code>create_function()</code> or by defining the function somewhere else, away from where it&#8217;s actually used. The above is clearly much better.</p>
<p>What else can we do with anonymous functions? In Ruby, they are the standard way of processing arrays. For example, if we want to process a set of files, adding a directory name at the beginning, we can do this:</p>
<pre class="brush: ruby">
files = [&#039;pdo.a&#039;,&#039;pdo.la&#039;,&#039;pdo.so&#039;,&#039;sqlite.a&#039;,&#039;sqlite.la&#039;,&#039;sqlite.so&#039;];
files_with_dir = files. map  { |f| &quot;modules/#{f}&quot; }
</pre>
<p>The snippet inside the braces is a function. <code>map</code> is the Ruby equivalent of PHP&#8217;s <code>array_map()</code>, except that Ruby is built to do this particular trick. But let&#8217;s try the equivalent with PHP 5.3. First we define the array:</p>
<pre class="brush: php">
$files = array(&#039;pdo.a&#039;,&#039;pdo.la&#039;,&#039;pdo.so&#039;,&#039;sqlite.a&#039;,&#039;sqlite.la&#039;,&#039;sqlite.so&#039;);
</pre>
<p>And then we process it:</p>
<pre class="brush: php">
$filesWithDir = array_map(
    function($f) { return &quot;modules/$f&quot; ; },
    $files
);
</pre>
<p>Interesting, but not necessarily better than the conventional alternative:</p>
<pre class="brush: php">
$filesWithDir = array();
foreach ($files as $file) {
    $filesWithDir[] = &quot;modules/$file&quot;;
}
</pre>
<p>Using array_map() seems like a realistic option, at least for some cases. It reads differently because it&#8217;s conceptually different, focusing on processing the entire array rather than one element at a time. You might find it cleaner. And in some cases, it will be clearly superior. If you have a slightly more complex structure than a simple one-dimensional array, you can use <code>array_map_recursive()</code> to simplify the code dramatically.</p>
<p>In <a href="http://blog.agilephp.com/2009/03/31/real-programming-with-php-53-part-2-javascript-style-classes/">part 2</a>, I&#8217;ll present an example of a JavaScript-style class composed of closures.</p>
<div style="margin-top: 10px; height: 15px;" class="zemanta-pixie"><a class="zemanta-pixie-a" href="http://reblog.zemanta.com/zemified/fcdb80d8-75b2-45a3-8655-b9e16459cab8/" 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=fcdb80d8-75b2-45a3-8655-b9e16459cab8" alt="Reblog this post [with Zemanta]"></a><span class="zem-script more-related"><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=Real%20programming%20with%20PHP%205.3%20%28part%201%29%3A%20array%20processing&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F03%2F19%2Freal-programming-with-php-53-part-1-array-processing%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/03/19/real-programming-with-php-53-part-1-array-processing/feed/</wfw:commentRss>
		<slash:comments>17</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>Type hints are not hints</title>
		<link>http://blog.agilephp.com/2009/02/14/type-hints-are-not-hints/</link>
		<comments>http://blog.agilephp.com/2009/02/14/type-hints-are-not-hints/#comments</comments>
		<pubDate>Sat, 14 Feb 2009 15:33:16 +0000</pubDate>
		<dc:creator>dagfinn</dc:creator>
				<category><![CDATA[PHP]]></category>

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



Image by Franco Folini via Flickr



As Kevlin Henney pointed out at the PHP UK Conference 2007, PHP type hints are not hints.
Rather, they are instructions to PHP to check the type. That may not be terribly important,
but it&#8217;s worth pointing out, since confusing terminology is less confusing if you understand how it&#8217;s confusing.
Anyway, I hereby [...]]]></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/78425154@N00/451819159"><img title="Graffiti: Hint" src="http://farm1.static.flickr.com/241/451819159_f99bada806_m.jpg" alt="Graffiti: Hint" width="240" height="180" /></a></dt>
<dd class="wp-caption-dd zemanta-img-attribution" style="font-size: 0.8em;">Image by <a href="http://www.flickr.com/photos/78425154@N00/451819159">Franco Folini</a> via Flickr</dd>
</dl>
</div>
</div>
<p>As <a class="zem_slink" title="Kevlin Henney" rel="wikipedia" href="http://en.wikipedia.org/wiki/Kevlin_Henney">Kevlin Henney</a> pointed out at the PHP UK Conference 2007, PHP type hints are not hints.<br />
Rather, they are instructions to PHP to check the type. That may not be terribly important,<br />
but it&#8217;s worth pointing out, since confusing terminology is less confusing if you understand how it&#8217;s confusing.</p>
<p>Anyway, I hereby apologize to the gods of programming for using the term and for the fact that I intend to keep on using it. <img src='http://blog.agilephp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </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/cda52132-d17c-4d56-a056-ebf19c605691/"><img class="zemanta-pixie-img" style="border: medium none; float: right;" src="http://img.zemanta.com/reblog_a.png?x-id=cda52132-d17c-4d56-a056-ebf19c605691" 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=Type%20hints%20are%20not%20hints&amp;linkurl=http%3A%2F%2Fblog.agilephp.com%2F2009%2F02%2F14%2Ftype-hints-are-not-hints%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/14/type-hints-are-not-hints/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
