<?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>Perlblogs &#187; oo</title>
	<atom:link href="http://perlblogs.com/category/oo/feed/" rel="self" type="application/rss+xml" />
	<link>http://perlblogs.com</link>
	<description>Posts from selected Perl bloggers</description>
	<lastBuildDate>Fri, 18 May 2012 19:03:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
<atom:link rel="hub" href="http://pubsubhubbub.appspot.com"/><atom:link rel="hub" href="http://superfeedr.com/hubbub"/>		<item>
		<title>Loaded for Werewolf</title>
		<link>http://www.modernperlbooks.com/mt/2012/03/loaded-for-werewolf.html</link>
		<comments>http://www.modernperlbooks.com/mt/2012/03/loaded-for-werewolf.html#comments</comments>
		<pubDate>Thu, 08 Mar 2012 23:47:39 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[cpan]]></category>
		<category><![CDATA[documentation]]></category>
		<category><![CDATA[legends]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[oo]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=6df64b711c252320a8903d22788346a6</guid>
		<description><![CDATA[Legend has it that Jean Chastel fired two shots and killed the beast of G&#38;eacute;vaudan. The beast attacked livestock and people in south-central France in the middle of the 18th century. Some say the beast killed over a hundred people....]]></description>
			<content:encoded><![CDATA[
        <p>Legend has it that <a
href="http://betedugevaudan.com/en/jean_chastel_en.html">Jean Chastel</a> fired
two shots and killed the <a href="http://betedugevaudan.com/en/">beast of
G&eacute;vaudan</a>.</p>

<p>The beast attacked livestock and people in south-central France in the
middle of the 18th century. Some say the beast killed over a hundred people.
The attacks ended after the deaths of two large wolves&mdash;one in 1765 and
the other by Chastel in 1767.</p>

<p>By the 20th century the legend had grown to include the story that Chastel
had melted down a medallion of the Virgin Mary to make two bullets of
silver.</p>

<p>In 1986, Fred Brooks used this metaphor to propose that no single technology
nor management technique could produce an order of magnitude improvement in
productivity, reliability, or simplicity within the decade. (Most people get
this quote very wrong. Most people haven't read the paper in detail or at
all.)</p>

<p>Perl 1 entered the public world in 1987.</p>

<p>Today (while solving hard problems), I realized that <a
href="http://moose.perl.org/">Moose</a> and its ecosystem&mdash;including
projects it's inspired, such as other declarative mechanisms for describing
classes and objects&mdash;may just represent an order of magnitude improvement
in productivity, reliability, and simplicity.</p>

<p>I write a lot less code. I write less repetitive code. My code is easier to
read and to maintain. My code is much more correct. My code is much more
flexible and easier to test. (Compilation error messages are much worse. That
doesn't bother me terribly, but keep it in mind.)</p>

<p>Keep your blessed hash references all you want and lament that kids these
days don't have to walk uphill in the snow both ways to stuff things in package
global variables like <code>@INC</code> and that we're lazy, fat slobs for
using CPAN modules for what you have done by hand since 1994, just as Moses did
and King James always intended...</p>

<p>... but I'm loaded for werewolf.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2012/03/09/loaded-for-werewolf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Null Objects, Error Handling, and Robustness</title>
		<link>http://www.modernperlbooks.com/mt/2012/02/null-objects-error-handling-and-robustness.html</link>
		<comments>http://www.modernperlbooks.com/mt/2012/02/null-objects-error-handling-and-robustness.html#comments</comments>
		<pubDate>Mon, 06 Feb 2012 18:28:15 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[modernperl]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[softwaredesign]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=ffcf277a3ae1133a4eef67dc1c96c540</guid>
		<description><![CDATA[A Practical Use for Macros in Perl generated several thoughtful comments. While Aristotle Pagaltzis identified the real semantic difficulty with the code I wanted to write (and mentioned the Null Object pattern, which I always keep in mind), Chas. Owens...]]></description>
			<content:encoded><![CDATA[
        <p><a href="http://www.modernperlbooks.com/mt/2012/02/a-practical-use-for-macros-in-perl.html">A Practical Use for Macros in Perl</a> generated several thoughtful comments. While <a href="http://plasmasturm.org/">Aristotle Pagaltzis</a> identified the real semantic difficulty with the code I wanted to write (and mentioned the <a href="http://www.c2.com/cgi/wiki?NullObject">Null Object pattern</a>, which I always keep in mind), <a href="http://wonkden.net/">Chas. Owens</a> asked perhaps the best <em>philosophical</em> question:</p>

<blockquote><em>Why not modify add_txn to reject undefs?</em></blockquote>

<p>The code in review is:</p>

<pre><code>while (my $stock = $stock_rs-&gt;next)
{
    my $pe_update = $self-&gt;analyze_pe( $stock );
    $stock_txn-&gt;add( $pe_update ) if $pe_update;

    my $cash_yield_update = $self-&gt;analyze_cash_yield( $stock );
    $analysis_txn-&gt;add( $cash_yield_update ) if $cash_yield_update;
}</code></pre>

<p>... and the near duplication obscures (to me) the point of the code. Both Aristotle and Chas. are right&mdash;perhaps it's clearer to allow <code>$transaction-&gt;add</code> to do nothing when it receives nothing. I write "perhaps" because I see the appeal of that change, but I'm not sure I like it.</p>

<p>As usual with my software, the system has a fundamental design principle:
either succeed in full or do nothing. It's fine to skip half of the analysis
steps if the data just isn't there. (The project as a whole can succeed if it's
only 60% correct; the joy of a margin of error. It's a lot more accurate than
that.)</p>

<p>I take this principle to mean that robustness is more important than
completeness. Skipping bad data and moving on is perfectly fine. The next run
may improve transient errors, and catastrophic errors will require human
intervention anyhow.</p>

<p>When these principles translate into design, I prefer to handle errors at
the point of detection and not spread error handling throughout the system.
All of these analysis methods <em>should</em> return something. When they
succeed, they return a hash reference mapping column names to values in a
database table. When these methods fail&mdash;whether the existing data isn't
sufficient to calculate updated values or something else went wrong&mdash;they
<code>return;</code>. As you well know, that's an empty list in list context
and <code>undef</code> in the scalar context of the example code.</p>

<p>Why add nothing to a transaction when I know there's nothing to add? Yes,
<code>add()</code> could check that it has nothing to do and do nothing, and
that's fine, but it seems like that expands the behavior of
<code>add()</code>'s API to include caller errors. Then again, the
<code>add()</code> method must check that each hash reference contains a value
for the transaction's bound primary key, or it will generate buggy output.</p>

<p>I suspect that both Aristotle and Chas. have in mind <a href="http://c2.com/cgi/wiki?JonPostel">Postel's Law</a>:</p>

<blockquote><em>Be generous in what you accept and picky about what you emit.</em></blockquote>

<p>The result might look something like:</p>

<pre><code>while (my $stock = $stock_rs-&gt;next)
{
    $stock_txn-&gt;add(    $self-&gt;analyze_pe( $stock )         );
    $analysis_txn-&gt;add( $self-&gt;analyze_cash_yield( $stock ) );
}</code></pre>

<p>This change has an advantage: it only necessitates a change in the
<code>add()</code> method. All of the <code>analyze_*()</code> methods can
continue to work as implemented.</p>

<p>Of course, there's a slight performance penalty to doing this. In my case,
it's immaterial, but it wouldn't be present with macros. This is an IO-bound
application anyhow, and the transaction manager exists to avoid very real, very
measured bottlenecks.</p>

<p>Finally, Aristotle's mention of the null object pattern was about
<em>real</em> objects, and not methods which return empty lists or hash
references. If that's your style, good for you&mdash;but it's not mine in this
case. While it's not obvious from the small snippets I've posted so far, the
responsibility of the analysis methods is smaller in scope than the
responsibility of the transaction objects. Coupling transaction management to
the analysis methods&mdash;in as much that they have to know about transactions
to return the right objects&mdash;would turn the design of the system inside
out. The result would very likely not be an improvement.</p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2012/02/06/null-objects-error-handling-and-robustness/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>You&#8217;re Already Using Dependency Injection</title>
		<link>http://www.modernperlbooks.com/mt/2011/08/youre-already-using-dependency-injection.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/08/youre-already-using-dependency-injection.html#comments</comments>
		<pubDate>Thu, 11 Aug 2011 17:07:18 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[dependencyinjection]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[talks]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=76534268443023b7f1213deb26f63c8d</guid>
		<description><![CDATA[Ben Hengst gave a talk at Portland Perl Mongers last night about dependency injection and inversion of control in Perl. He said something completely true. &#34;You've probably already done this, even though you didn't know it was called this.&#34; At...]]></description>
			<content:encoded><![CDATA[
        <p><a href="http://notbenh.info/">Ben Hengst</a> gave a talk at <a
href="http://pdx.pm.org/">Portland Perl Mongers</a> last night about dependency
injection and inversion of control in Perl. He said something completely true.
"You've probably already done this, even though you didn't know it was called
this."</p>

<p>At its core, dependency injection is a formalization of the design principle "Don't hard-code your dependencies." Consider the code:</p>

<pre><code>sub fetch
{
    my ($self, $uri) = @_;
    my $ua           = LWP::UserAgent-&gt;new;
    my $resp         = $ua-&gt;get( $uri );

    ...
}</code></pre>

<p>That's not <em>bad</em> code by any means, but it's a little too specific
and a little less generic due to the presence of the literal string
<code>LWP::UserAgent</code>. That might be fine for your application, but that
hard-coding introduces a coupling that can work against other uses of this
code. Imagine testing this code, for example. While you <em>could</em> use <a
href="http://search.cpan.org/perldoc?Test::MockObject">Test::MockObject</a> to
intercept calls to <code>LWP::UserAgent</code>'s constructor, that approach
manipulates Perl symbol tables to work around a hard coded dependency.</p>

<p>An alternate approach uses a touch of indirection to allow for greater
genericity:</p>

<pre><code>use Moose;
<strong>has 'ua', is =&gt; 'ro', default =&gt; sub { LWP::UserAgent-&gt;new };</strong>

sub fetch
{
    my ($self, $uri) = @_;
    <strong>my $ua           = $self-&gt;ua;</strong>
    my $resp         = $ua-&gt;get( $uri );

    ...
}</code></pre>

<p>Now the choice of user agent is up to the code which constructs this object.
If it provides a <code>ua</code> to the constructor, <code>fetch()</code> will
use that. Otherwise, the default behavior is to use <code>LWP::UserAgent</code>
as before.</p>

<p>Adding one line of code and changing one line of code has provided much more flexibility.</p>

<p>An alternate approach is to allow setting <code>ua</code> through an
accessor instead of a constructor, but as far as I can tell the only reason to
do this is if you're stuck in <a href="http://www.bartleby.com/42/638.html">The
Land of the Java Bean Eaters</a>.</p>

<p>While the existing literature on inversion of control and dependency
injection tends to throw around big words which have the effect of obfuscating
rather than enlightening, the basic concepts is simple. You've probably already
done it. Now you know what it's called and why it's useful, and probably also
can find ways to use it where it helps.</p>

<p><em>(See also: how you select a DBD with <a href="http://search.cpan.org/perldoc?DBI">DBI</a>.)</em></p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/08/11/youre-already-using-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Count the (Possible) Bugs in this Code</title>
		<link>http://www.modernperlbooks.com/mt/2011/05/count-the-possible-bugs-in-this-code.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/05/count-the-possible-bugs-in-this-code.html#comments</comments>
		<pubDate>Mon, 23 May 2011 18:20:30 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[interfaces]]></category>
		<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[perl5]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[One sign of a good interface is the degree to which it encourages users to do the right thing and discourages users from doing the wrong thing. While a malicious or distracted or inexperienced user may still do things incorrectly,...]]></description>
			<content:encoded><![CDATA[
        <p>One sign of a good interface is the degree to which it encourages users to
do the right thing and discourages users from doing the wrong thing. While a
malicious or distracted or inexperienced user may still do things incorrectly,
a good interface reduces that possibility.</p>

<p>It's possible&mdash;even advisable&mdash;to analyze buggy code to see if the
bugs point to misfeatures in the interfaces. Plenty of bugs come from
misunderstandings of requirements, but plenty of bugs lurk in interfaces which
are unclear or difficult to use correctly.</p>

<p>Consider this snippet of code:</p>

<pre><code>use Moose;

has 'summary', is =&gt; 'rw';

around summary =&gt; sub
{
    my ($orig, $self) = splice @_, 0, 2;
    return $self-&gt;$orig() unless @_;
    my $summary       = shift;

    return $self-&gt;$orig() unless length $summary;

    my $content = $self-&gt;remove_markup( $summary );
    return '' unless $content;

    $self-&gt;$orig( $content );
};</code></pre>

<p>This snippet of Moose-based code declares an attribute named
<code>summary</code> with an autogenerated accessor and mutator of
<code>$object-&gt;summary</code>. It also wraps this autogenerated method with
code to sanitize any data set through the mutator by removing markup.</p>

<p>Everything <em>seems</em> straightforward, but consider all of the parts of
the interface which might go wrong. (This is not a criticism of Moose, which
does the best it can; it's an exploration of language and API design which just
happened to come up as I debugged some very buggy code I wrote.)</p>

<pre><code>my ($orig, $self) = splice @_, 0, 2;</code></pre>

<p>Perl 5's minimal argument handling nevertheless has some common idioms. One
of those is that <code>$self</code> is the first argument to all instance
methods. Is this an instance method? Sort of. It's also a wrapper around an
instance method which may or may not need to redelegate to the wrapped method
in various ways. Thus this wrapper needs access to the wrapped method
somehow.</p>

<p><a name="footnote_one_source"></a>The Moose developers chose to provide the
wrapped method as a code reference passed as the first argument to the wrapper,
mostly because this is the least worst approach [ <a href="http://www.modernperlbooks.com/mt/2011/05/count-the-possible-bugs-in-this-code.html#least_worst">1</a>
]. You can't really add syntax to Perl 5 within the scope of this wrapper even
with <a href="http://search.cpan.org/perldoc?Devel::Declare">Devel::Declare</a>
without rewriting the op tree of the method itself to get at the wrapped method
somehow, because Perl 5's internals know nothing about this technique. Besides
that, D::D is a heavy hammer to pull out.</p>

<p>(Again, <a
href="http://www.modernperlbooks.com/mt/2011/01/what-else-a-method-keyword-could-do.html">sometimes
adding syntax to Perl itself makes otherwise intractable problems
simple</a>.)</p>

<p>Passing this parameter at the end of <c>@_</c> would lead to the even more
awkward idiom of:</p>

<pre><code>around 'summary' =&gt; sub
{
    my $orig = pop;
    my $self = shift;
    ...
};</code></pre>

<p>The <code>splice</code> approach is the least worst way I've found to deal
with the situation where I have variadic argument counts to differentiate
between attribute access and attribute mutation.</p>

<p>One problem remains: this wrapper only matters for the mutation case. I'm
starting to believe that variadic redispatch within user code is a code smell
of the rotting vegetation variety.</p>

<p>If Perl 5 supported multiple dispatch even only on the <em>number</em> of
arguments provided to a method, this code would not be a problem. The wrapper
could apply only to the case where the method took one or more arguments and
would leave the accessor case of zero arguments unmodified.</p>

<p>The most right solution in my case is to change the name of the mutator to
<code>set_summary()</code>... except that that's only the obvious change in the
local case. For the sake of consistency with the rest of the system, I ought to
change every mutator's name to <code>set_<em>foo</em></code>: a large change.
It's worth doing, but I should have done it from the start, if I'd predicted
that a strict separation between setting and getting were necessary to reduce
the possibility of bugs in wrapped methods.</p>

<p>Consider also what happens if you don't take the <code>splice</code>
approach but <em>do</em> follow the common redispatching idiom:</p>

<pre><code>around summary =&gt; sub
{
    my ($orig, $self, @new_values) = @_;
    return $self-&gt;$orig() if @_ == 2;

    ...

    $self-&gt;$orig( @_ );
};</code></pre>

<p>I made that mistake too. It was easy enough to spot after DBIx::Class gave
me odd errors about not knowing how to store a coderef in a column that should
only contain text.</p>

<p>Again, this isn't Moose's fault. It does the best it can with the features
Perl 5 provides. Yet imagine if Perl 5 knew what an invocant was and understood
something about wrapping. (You can even unify redispatching to an overridden
parent method in this&mdash;and while you're at it, fix the <a
href="http://search.cpan.org/perldoc?SUPER">SUPER</a> bug.) The syntax might
look like:</p>

<pre><code>around 'summary' => method
{
    return $self-&gt;*around::original() unless @_;
    my $summary       = shift;

    return unless length $summary;

    my $content = $self-&gt;remove_markup( $summary );
    return '' unless $content;

    $self-&gt;&around::original( $content );
};</code></pre>

<p>Perhaps the star selector syntax isn't the right syntax to identify a
different dispatch mechanism than simple name-based lookup, but you get the
idea.</p>

<p>Until then, I'll be looking for an easy way to rename all of my
mutators.</p>

<hr />

<p>[1] <a name="least_worst"></a> Least worst? Consider the alternatives. If Moose
provided an internal mechanism to set attributes directly (and <em>not</em>
through direct hash access, which is prima facie the worst possible access
mechanism), it would likely need access control to restrict direct mutation to
declaring classes and their immediate descendents or applied roles. Figure out
<em>that</em> system. Now strengthen it against everyone who suddenly discovers
that a quick hack here and there will speed up synthetic benchmarks by a couple
of percent and break the carefully constructed encapsulation, and ... well,
welcome to Perl 5. (<a href="http://www.modernperlbooks.com/mt/2011/05/count-the-possible-bugs-in-this-code.html#footnote_one_source">back</a>)</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/05/23/count-the-possible-bugs-in-this-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing DBIx::Class Models without the Database</title>
		<link>http://www.modernperlbooks.com/mt/2011/05/testing-dbix-models-without-the-database.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/05/testing-dbix-models-without-the-database.html#comments</comments>
		<pubDate>Thu, 19 May 2011 00:55:06 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[dbixclass]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[roles]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[DBIx::Class is the first ORM I've found which provides more benefits than headaches. It's not perfect&#38;mdash;it has a learning curve&#38;mdash;but its power and flexibility have simplified several of my projects. One of my few ambivalences toward DBIC is that it...]]></description>
			<content:encoded><![CDATA[
        <p><a href="http://search.cpan.org/perldoc?DBIx::Class">DBIx::Class</a> is the
first ORM I've found which provides more benefits than headaches. It's not
perfect&mdash;it has a learning curve&mdash;but its power and flexibility have
simplified several of my projects.</p>

<p>One of my few ambivalences toward DBIC is that it commingles database
operations (create, retrieve, update, and destroy) with model-specific
operations ("level up this character", "sell the magic sword", "deactivate the
smoke trap"). This is <em>useful</em> in that my objects have smart persistence
and updating and relationship tracking provided by their DBICness, but it's
<em>difficult</em> in that sometimes I want a stricter separation of database
concerns from data model concerns.</p>

<p>Suppose I want to test that a document processing model can successfully
filter out many hundreds of thousands of algorithmically generated permutations
of unwanted data. Suppose, as is the case, that these documents are DBIC
objects normally retrieved from a database. A test database might seem like
just the thing for data-driven testing, but in this case it seems <em>more</em>
work to generate a large transient database full of hundreds of thousands of
documents to satisfy the constraints of DBIC.</p>

<p>In other words, I want a way to generate a new model object programmatically
without having to store it in and retrieve it from a database. (Alex Hartmaier and Matt S. Trout both reminded me of the <code>$rs-&gt;new_result()</code> method which creates an object given the appropriate resultset but does not store it in the database.)</p>

<p>I <em>do </em> have tests which verify that the storage concerns behave as
appropriate. They represent a small investment in mock data which sufficiently
exercises all of the cases my code needs to handle. My other test concerns have
little to do with the database itself. They care about <em>what</em> the model
objects do with their data, not <em>how</em> they get that data.</p>

<p>Thank goodness DBIC is compatible with <a href="http://moose.perl.org/">Moose</a>.</p>

<p>I extracted all of the non-database model methods into a role. That role
requires the accessors the database model provides for persistent data. I
created a very simple dummy class which has those necessary attributes and
performs that role. Then I wrote a very, very simple loader function which
generates the necessary data algorithmically, instantiates instances of the
dummy class, and tests the role's methods.</p>

<p>(I plan to write a longer article for Perl.com showing example code.)</p>

<p>The result is a model class which consists solely of the code generated from
<a
href="http://search.cpan.org/perldoc?DBIx::Class::Schema::Loader">DBIx::Class::Schema::Loader</a>
and a <code>with</code> statement to apply a couple of roles. The tests are in
two parts: one tests the model-specific code. The other tests the
persistence-specific code, itself a combination of the generated code and
another role which collects the remaining persistence behavior.</p>

<p>Even though both roles have an obvious coupling in terms of providing
necessary behavior to the model (and to each other), decoupling them in terms
of storage provides much improved testability&mdash;and, I suspect, more
opportunities for reuse and genericity throughout the system.</p>

<p>While <a
href="http://www.modernperlbooks.com/mt/2009/04/the-why-of-perl-roles.html">explanations
of the value of Perl roles</a> often focus on reusability and the separation of
similar concerns from otherwise unrelated classes, roles can also provide a
separation between dissimilar behaviors and concerns. In this case, it doesn't
matter to the role methods <em>where</em> the data comes from (a live database,
a testing database, an algorithm, hard-coded in a test case, the command line,
wherever). It only matters that that data is there.</p>

<p>This technique doesn't always work. This technique isn't always appropriate.
This technique does not replace verification that your behavior roles
interoperate with your persistence models appropriately. Even so, it has
simplified a lot of my code and improved my tests greatly.</p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/05/19/testing-dbixclass-models-without-the-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Decoupling, Testability, and Synthetic Attributes</title>
		<link>http://www.modernperlbooks.com/mt/2011/05/decoupling-testability-and-synthetic-attributes.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/05/decoupling-testability-and-synthetic-attributes.html#comments</comments>
		<pubDate>Sat, 14 May 2011 20:04:56 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[perl5]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[(or, You Could Have Invented Dependency Injection) I've been refactoring an existing system from a prototype to a well-designed and maintainable system. Part of that process is finding a better design. Part of that process is improving test coverage to...]]></description>
			<content:encoded><![CDATA[
        <p><em>(or, You Could Have Invented Dependency Injection)</em></p>

<p>I've been refactoring an existing system from a prototype to a well-designed
and maintainable system. Part of that process is finding a better design. Part
of that process is improving test coverage to find and fix bugs.</p>

<p>Something fascinating happens during that process if you pay attention.</p>

<p>Because the design of the project is fluid at this point, I have free reign
to redesign to make testing easier. Because test coverage is spotty in places,
redesigning to make testing easier is almost a necessity. Fortunately, the
project is small enough and communication with the stakeholders easy enough
that determining <em>what</em> the code should do where it's not clear is
easy.</p>

<p>Plenty of people criticize test-driven development as if it were an
iron-clad rule of law, where every line of code must have at least one
associated test case, and if you do that, you get a badge and some grape
flavored juice to hold you over until the spaceship comes. If that were the
only benefit, that would indeed be a fair criticism&mdash;but how do you test
this code?</p>

<pre><code>sub save_to
{
    my ($self, $dirpath) = @_;

    my $filepath = File::Spec-&gt;catfile( $dirpath, $self-&gt;cached_file );

    my $i = Imager-&gt;new( file =&gt; $self-&gt;full_file );
    return $self-&gt;invalidate() unless $i;

    my $width  = $i-&gt;getwidth;
    my $height = $i-&gt;getheight;

    # verify size
    return $self-&gt;invalidate()
           if MyCoolApp::Exclude-&gt;image_size( $width, $height );

    my @resize = $self-&gt;should_resize( $width, $height );

    try
    {
        $i = $i-&gt;scale( @resize ) if @resize;
        $i-&gt;write( file =&gt; $filepath );
        unlink $self-&gt;full_file;
        $self-&gt;state( 'FETCHED' );
        $self-&gt;full_file( $filepath );
    }
    catch { warn $_; $self-&gt;invalidate };

    return 1;
}</code></pre>

<p>This code will not be trivial to test. Perl 5 has a few idioms for testing
the existence of files in the filesystem. With some careful use of <a
href="http://search.cpan.org/perldoc?File::Temp">File::Temp</a>, it's possible
to verify that a file which did not exist before the call being tested exists
after the call, but the rest of this code has other difficulties.</p>

<p>The hardest part of this code to test comes from the hard-coded call to the
<a href="http://search.cpan.org/perldoc?Imager">Imager</a> constructor. I
<em>could</em> hijack the loading of Imager with <a
href="http://search.cpan.org/perldoc?Test::MockObject::Extends">Test::MockObject::Extends</a>
and test all of the paths through this method by changing the mock Imager's
behavior, but that would couple of the details of the test too tightly to the
details of the code being tested.</p>

<p>This method's biggest problem is that it does too much. It creates an Imager
object. It tests to see if the image represented should be excluded from
saving. It resizes the image. Then, finally, it saves the image. All of this
behavior made sense when the only operation performed against this API was
"save this image, if applicable" but these operations are very obviously
distinct operations confused in one spot when trying to <em>test</em> this
API.</p>

<p>This is where the people who dismiss TDD as a only brain-numbing checklist
of rote behavior are wrong. I'd never let myself write a method with this many
separate concerns if I had written it with TDD, but I can admit that I'd write
code with this many separate concerns if I'd written prototype, just get it
working, see of it's possible code. (I <em>did</em> write the exclusion
code.)</p>

<p>Years ago I would have forged ahead to dummy up an entire Imager, just to
get full test coverage. Fortunately, this code uses <a
href="http://moose.perl.org/">Moose</a>.</p>

<p>Moose?</p>

<p>The design patterns people have a term called <a
href="http://c2.com/cgi/wiki?InversionOfControl">Inversion of Control</a> and a
specific grouping of techniques in a family called <a
href="http://c2.com/cgi/wiki?DependencyInjection">Dependency Injection</a>. You
can get lost in the architecture astronaut nature of the discussion, but the
basic principle is sound: avoid hard-coding dependencies in your code.</p>

<p>In other words, the most suspect part of this method is the line:</p>

<pre><code>    my $i = Imager-&gt;new( file =&gt; $self-&gt;full_file );</code></pre>

<p>... because of the very tight coupling between this module and Imager.</p>

<p>You may think now "Wait, but you <em>need</em> the <em>behavior</em> of
Imager for the code to work correctly!" and you're correct to do so. That's
absolutely right. This code needs the <em>behavior</em> of the Imager object,
and this code is tied to the API of the Imager object, but this code itself
does not have to be responsible for <em>instantiating</em> the Imager
object.</p>

<p>If you already knew that, give yourself a gold star. If you're now thinking
"Yeah, but why does that matter?" or "What?", read the previous paragraph
again. It's subtle, but it's important.</p>

<p>Moose supports something I'll call synthetic attributes. They're attributes
of your object built from the values of other attributes. You're likely to
encounter them when they're built lazily. Consider if I added an
<code>imager</code> attribute to this class:</p>

<pre><code>has 'imager', is =&gt; 'ro', lazy_build =&gt; 1;

sub _build_imager
{
    my $self = shift;
    return Imager-&gt;new( file =&gt; $self-&gt;full_file );
}</code></pre>

<p>That performs one very nice feature of decoupling the creation of the Imager
object from the method I want to test. If that's the only value of the new
synthetic attribute, it's still useful. Yet that attribute has greater
serendipities:</p>

<pre><code>sub test_save_to
{
    my $module = shift;
    my $image  = $module-&gt;new(
        filename =&gt; 'my_file.gif',
        state    =&gt; 'FETCH',
        validity =&gt; 10,
        imager   =&gt; undef,
        validity =&gt; 0
    ) );
    my $result = $image-&gt;save_to( 'some_dir' );

    ok ! $result, 'save_to() should return false without valid imager';
    ok ! $image-&gt;is_valid, '... invalidating image';
}</code></pre>

<p>Extracting this hard-coded call into a synthetic attribute with Moose allows
code which creates these image objects to provide their own values for the
imager synthetic attribute. The test is now in control over what's provided. It
can use a real Imager object or a mocked Imager object. It can allow the lazy
builder to create a real object.</p>

<p>One small act of extraction (and, as usual, intelligent default behavior in
Moose) has turned a method which is difficult to test into something much more
tractable. Testing even the hard-coded call itself was <em>possible</em> in
Perl 5, especially with the utilities of CPAN modules which let you scrounge
around in namespaces, but little bit of care and a little bit of abstraction
and decoupling and encapsulation make the code and the tests more robust.</p>

<p>(For full disclosure: I had a fleeting thought at first "With
<code>imager()</code> as an accessor, I can subclass the class I want to test
locally, override that method, and return what I want. That's not
<em>strict</em> dependency injection by any means, but I can explain it in
terms of DI as a metaphor." A moment later I realized how easily Moose supports
DI if you structure your code in this way and was glad I don't have to
overdesign the tests.)</p>

<p>This is the sort of writing I didn't have time to get into in detail in <a href="http://www.amazon.com/gp/product/0977920151?ie=UTF8&tag=onyneopre-20">Modern Perl: the book</a>, but is well within the scope of what the potential authors of the Moose book want to cover and very much in the spirit of what a new Perl Testing book will discuss. Hint, hint.</p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/05/14/decoupling-testability-and-synthetic-attributes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pains of the Past, Begone!</title>
		<link>http://www.modernperlbooks.com/mt/2011/05/pains-of-the-past-begone.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/05/pains-of-the-past-begone.html#comments</comments>
		<pubDate>Thu, 05 May 2011 18:40:01 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[perl5]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[Still not convinced that Moose cuts the Gordian knot that tied the Perl 5 world up in spaghetti knots for so many years? Review some of the discussions of Perl 5 OO in the pre-Moose world, especially after Apocalypse 12...]]></description>
			<content:encoded><![CDATA[
        <p>Still not convinced that <a href="http://moose.perl.org/">Moose</a> cuts the Gordian knot that tied the Perl 5 world up in spaghetti knots for so many years? Review some of the discussions of Perl 5 OO in the pre-Moose world, especially after Apocalypse 12 came out and shone a light on the path out of darkness.</p>

<p>I amused myself far too much by reading <a href="http://perlmonks.org/?node_id=510974">A Class:: module I don't want to write</a> and <a href="http://perlmonks.org/?node_id=511014">Can I please have *simple* modules?</a>, for example.</p>

<p>My rule is simple: Moose has made me forget many, many little problems that I used to have in the same way that Perl has made me forget many, many little problems that I used to have. (I'd even forgotten I'd written an article called "Seven Sins of Perl OO" five years ago. With Moose, only one of those sins is still a problem.)</p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/05/05/pains-of-the-past-begone/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reuse is Merely a Happy Accident</title>
		<link>http://www.modernperlbooks.com/mt/2011/05/reuse-is-merely-a-happy-accident.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/05/reuse-is-merely-a-happy-accident.html#comments</comments>
		<pubDate>Mon, 02 May 2011 03:56:16 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[novices]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[perl]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[What is the purpose of object orientation? If you, like me, first encountered the term in the popular working programmer literature of the '90s (or if you've read Microserfs), you might have heard that the purpose of OO is to...]]></description>
			<content:encoded><![CDATA[
        <p>What is the purpose of object orientation?</p>

<p>If you, like me, first encountered the term in the popular working programmer literature of the '90s (or if you've read <a href="http://www.amazon.com/Microserfs-Douglas-Coupland/dp/0060987049?tag=onyneopre-20">Microserfs</a>), you might have heard that the purpose of OO is to enable the deliberate reuse of unique and well-defined software components.</p>

<p>If you learned structured programming, whether earlier in the history of programming language development or because objects were a fad until Sun's marketing budget displaced IBM's marketing budget, you might have heard that the purpose of functions is to enable the deliberate reuse of unique and well-defined software components.</p>

<p>I write this knowing full well that in a few minutes I need to modify a
piece of code which uses multiple CPAN modules, many of them defined, tested,
deployed, and loved very well. With that in mind, I still believe that reuse as
a primary design principle is often a fool's goal.</p>

<p>Last week's example of <a href="http://www.modernperlbooks.com/mt/2011/04/abstraction-versus-mock-objects.html">abstraction versus mock objects</a> elicited thoughtful comments from <a href="http://perlalchemy.blogspot.com/">Zbigniew Lukasiak</a> and Andreas Mock relating to the single responsibility principle, design patterns, and dependency injection. These concerns are important in the sense that contrast and shading and hue are important concerns in creating great artwork.</p>

<p>Yet somehow the false notion that design is primarily an exercise in identifying, codifying, and extracting reusable components is pervasive, especially in literature intended for novices. (Perhaps novices sigh with relief when they finally get a single function or class working correctly, thinking to themselves "Thank goodness I shall never do this again!")</p>

<p>In 1999 I might not have created a helper class to solve my testing problem
from last week. (Why multiply entities unnecessarily? I'm not writing ravioli
code here!) I might have struggled through mocking DBIC row objects and priding
myself on the thoroughness of my testing of all of the picky little
details.</p>

<p>In 2011 I congratulate myself more on the code I don't have to write&mdash;not because I'm reusing implementation details but because <em>I've minimized the details any particular piece of code has to understand</em>.</p>

<p>That's why the <a
href="http://onyxneon.com/books/modern_perl/index.html">Modern Perl book</a>
explains functions primarily as a way of naming and encapsulating discrete
units of behavior and objects as discrete identities with single, well-defined
responsibilities.</p>

<p>Reuse is well and good when it happens, but reuse happens best <em>because
of</em> sensible design. It's not the primary goal of software design. Nor
should it be. It's a serendipity born of the fundamental design concerns of
naming and encapsulation.</p>

<p>Let us teach these useful truths to novices instead of the airy lies they
will waste their time pursuing.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/05/02/reuse-is-merely-a-happy-accident/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reuse is Merely a Happy Accident</title>
		<link>http://www.modernperlbooks.com/mt/2011/05/reuse-is-merely-a-happy-accident.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/05/reuse-is-merely-a-happy-accident.html#comments</comments>
		<pubDate>Mon, 02 May 2011 03:56:16 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[novices]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[perl]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[What is the purpose of object orientation? If you, like me, first encountered the term in the popular working programmer literature of the '90s (or if you've read Microserfs), you might have heard that the purpose of OO is to...]]></description>
			<content:encoded><![CDATA[
        <p>What is the purpose of object orientation?</p>

<p>If you, like me, first encountered the term in the popular working programmer literature of the '90s (or if you've read <a href="http://www.amazon.com/Microserfs-Douglas-Coupland/dp/0060987049?tag=onyneopre-20">Microserfs</a>), you might have heard that the purpose of OO is to enable the deliberate reuse of unique and well-defined software components.</p>

<p>If you learned structured programming, whether earlier in the history of programming language development or because objects were a fad until Sun's marketing budget displaced IBM's marketing budget, you might have heard that the purpose of functions is to enable the deliberate reuse of unique and well-defined software components.</p>

<p>I write this knowing full well that in a few minutes I need to modify a
piece of code which uses multiple CPAN modules, many of them defined, tested,
deployed, and loved very well. With that in mind, I still believe that reuse as
a primary design principle is often a fool's goal.</p>

<p>Last week's example of <a href="http://www.modernperlbooks.com/mt/2011/04/abstraction-versus-mock-objects.html">abstraction versus mock objects</a> elicited thoughtful comments from <a href="http://perlalchemy.blogspot.com/">Zbigniew Lukasiak</a> and Andreas Mock relating to the single responsibility principle, design patterns, and dependency injection. These concerns are important in the sense that contrast and shading and hue are important concerns in creating great artwork.</p>

<p>Yet somehow the false notion that design is primarily an exercise in identifying, codifying, and extracting reusable components is pervasive, especially in literature intended for novices. (Perhaps novices sigh with relief when they finally get a single function or class working correctly, thinking to themselves "Thank goodness I shall never do this again!")</p>

<p>In 1999 I might not have created a helper class to solve my testing problem
from last week. (Why multiply entities unnecessarily? I'm not writing ravioli
code here!) I might have struggled through mocking DBIC row objects and priding
myself on the thoroughness of my testing of all of the picky little
details.</p>

<p>In 2011 I congratulate myself more on the code I don't have to write&mdash;not because I'm reusing implementation details but because <em>I've minimized the details any particular piece of code has to understand</em>.</p>

<p>That's why the <a
href="http://onyxneon.com/books/modern_perl/index.html">Modern Perl book</a>
explains functions primarily as a way of naming and encapsulating discrete
units of behavior and objects as discrete identities with single, well-defined
responsibilities.</p>

<p>Reuse is well and good when it happens, but reuse happens best <em>because
of</em> sensible design. It's not the primary goal of software design. Nor
should it be. It's a serendipity born of the fundamental design concerns of
naming and encapsulation.</p>

<p>Let us teach these useful truths to novices instead of the airy lies they
will waste their time pursuing.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/05/02/reuse-is-merely-a-happy-accident/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Abstraction versus Mock Objects</title>
		<link>http://www.modernperlbooks.com/mt/2011/04/abstraction-versus-mock-objects.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/04/abstraction-versus-mock-objects.html#comments</comments>
		<pubDate>Thu, 28 Apr 2011 15:34:18 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[moose]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[perl5]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[One of my projects switched persistence mechanisms from KiokuDB to DBIx::Class recently. KiokuDB had the benefit of simplicity&#38;mdash;it was very easy to develop the initial project without worrying about managing table schemas and upgrades, but as the project matured, the...]]></description>
			<content:encoded><![CDATA[
        <p>One of my projects switched persistence mechanisms from <a
href="http://search.cpan.org/perldoc?KiokuDB">KiokuDB</a> to <a
href="http://search.cpan.org/perldoc?DBIx::Class">DBIx::Class</a> recently.
KiokuDB had the benefit of simplicity&mdash;it was very easy to develop the
initial project without worrying about managing table schemas and upgrades, but
as the project matured, the benefits of DBIC became more apparent.</p>

<p>I like how KiokuDB persists plain old Moose objects. If you understand how
your object graph works, there's little effective difference between a Moose
object you create yourself or one you retrieve from your object store. Less so
DBIC objects, in my experience. This isn't a flaw. It's merely a
difference.</p>

<p>The difference became apparent when I started to port a fundamental test
file as part of this migration. This test file exercises the document parser.
As part of the application, the document parser uses a variant of the <a
href="http://readability.com/">Readability</a> algorithm to extract the
meaningful portions of HTML documents. The test file itself uses a data-driven
approach, where a <em>t/files/documents/</em> directory holds multiple YAML
files containing real data we've encountered along with the expected (correct)
results.</p>

<pre><code>#! perl

use Modern::Perl;
use Test::More;
use YAML::XS;

use lib 't/lib';

__PACKAGE__-&gt;main( 'App::DocParser', @ARGV );

sub create_docparser
{
    return App::DocParser-&gt;new(
        url       =&gt; 'http://www.example.com/some_url',
        url_base  =&gt; 'http://www.example.com/',
        @_,
    );
}

sub main
{
    my ($test, $module, @files) = @_;
    use_ok( $module ) or exit;

    if (@files)
    {
        $test-&gt;run_file_content_tests( $module, @files );
    }
    else
    {
        $test-&gt;test_find_content_files( $module );
    }

    done_testing();
}

sub test_find_content_files
{
    run_file_content_tests( @_, glob 't/files/documents/*.yaml' );
}

sub run_file_content_tests
{
    my ($test, $module, @files) = @_;

    for my $file (@files)
    {
        my $example   = YAML::XS::LoadFile( $file );
        my $docparser = create_docparser( %$example );

        like $docparser-&gt;content, $example-&gt;{content_regex},
        "DocParser should find matching content for $example-&gt;{desc}";

        is 0 + @{ $docparser->links }, $example->{link_count},
            '... with the right number of links';
    }
}</code></pre>

<p>The previous version of this code created <code>App::Document</code>
objects&mdash;instances of the same class persisted into the object graph with
KiokuDB&mdash;and called functions in the <code>DocParser</code> namespace to
find various pieces of context. A straightforward port of this test file to
DBIC meant I'd have had to figure out how to instantiate dummy DBIC-alike
objects representing documents to pass to the <code>DocParser</code>
functions.</p>

<p>I thought about that for a few minutes. I pondered reaching for <a
href="http://search.cpan.org/perldoc?Test::MockObject::Extends">Test::MockObject::Extends</a>.
Then I didn't.</p>

<p>What's important in this test isn't that <code>App::DocParser</code>
conforms to a specific interface governed by the persistence layer. That's
irrelevant. Its only relevance is <em>how well</em> it identifies and extracts
relevant information from given data.</p>

<p>I turned that namespace full of utility functions into a class. I gave that
class the specific attributes on which it needs to operate, effectively giving
instances of the class the responsibility to manage the data on which they
operate. You can see the result: a simple constructor call creates a
<code>DocParser</code> object without worrying about setting up test data in an
example database or building a mock object framework which behaves sufficiently
like a DBIC row object.</p>

<p>I really like the object responsibility pattern which Moose seems to
encourage, where you create an object by passing all relevant data to its
constructor and then operate on that data as needed (perhaps governed by
laziness in attribute accessors). You get the benefit of being able to assume
that a constructed object is in a safe and sane state as well as a decoupling
of data dependencies.</p>

<p>Once I realized that this approach would lead to better code, it took twenty
minutes to Moosify the document parser and one minute to change a couple of
lines of code to port the test to the new framework. I count that as a sign of
effective design.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/04/28/abstraction-versus-mock-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

