<?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; languagedesign</title>
	<atom:link href="http://perlblogs.com/category/languagedesign/feed/" rel="self" type="application/rss+xml" />
	<link>http://perlblogs.com</link>
	<description>Posts from selected Perl bloggers</description>
	<lastBuildDate>Mon, 06 Feb 2012 20:47:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<atom:link rel="hub" href="http://pubsubhubbub.appspot.com"/><atom:link rel="hub" href="http://superfeedr.com/hubbub"/>		<item>
		<title>A Practical Use for Macros in Perl</title>
		<link>http://www.modernperlbooks.com/mt/2012/02/a-practical-use-for-macros-in-perl.html</link>
		<comments>http://www.modernperlbooks.com/mt/2012/02/a-practical-use-for-macros-in-perl.html#comments</comments>
		<pubDate>Fri, 03 Feb 2012 20:46:43 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[perl5]]></category>
		<category><![CDATA[refactoring]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=5cffcd700874d4b530e9c045dc4412b1</guid>
		<description><![CDATA[People occasionally ask for practical examples of macros when I lament the lack of macros in Perl 5. While I'm usually pleased at the degree to which Perl lets me design code to get and stay out of my way,...]]></description>
			<content:encoded><![CDATA[
        <p>People occasionally ask for practical examples of macros when I lament <a
href="http://www.modernperlbooks.com/mt/2011/11/what-the-perl-5-compiler-modules-could-have-been.html">the
lack of macros in Perl 5</a>. While I'm usually pleased at the degree to which
Perl lets me design code to get and stay out of my way, sometimes its
abstractions just aren't quite <em>enough</em> enough to remove all of the
duplication available.</p>

<p>(I've been refactoring one of our business projects in preparation for another round of deployment in the next couple of weeks. We could launch without these improvements, but administrative work took almost two weeks longer than the afternoon I'd planned for it, so I decided it was worth my time to <a href="http://www.modernperlbooks.com/mt/2011/11/on-technical-friction.html">reduce technical friction</a> so that further improvements are easier. More users means more work, so why not accelerate that work while I have the chance? I have another longer technical post to write to praise the use of Moose roles for a plugin system and to show off the stupidly-great task launcher, but that's for later.)</p>

<p>I found myself writing two code couplets that were similar enough they
triggered my "Hey, refactor away this duplication!" alert. It's extra
sensitive, because I <em>know</em> I'll have a few more couplets like this in
the very near future:</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>The <code>*_txn</code> variables contain objects representing deferred and
scoped SQL updates. I'll talk about that at <a
href="http://act.yapcna.org/2012/">YAPC::NA 2012</a> in <a
href="http://act.yapcna.org/2012/talk/50">When Wrong is Better</a>.</p>

<p>The general pattern is this: for every stock in the appropriate resultset,
call a method in this plugin. The method will return nothing if it fails (or
has nothing to do) or it will return data to be added to the appropriate
transaction. I have at least two types of transactions available here at the
moment, and may have more later: one transaction updates stock data and the
other updates analysis data.</p>

<p>I have several options. I could rework the data model so that this stage
always only updates one transaction, in which the loop body could instead look
like:</p>

<pre><code>{
    for my $method (qw( analyze_pe analyze_cash_yield ))
    {
        next unless my $result = $self->$method( $stock );
        $txn->add( $result );
    }
}</code></pre>

<p>This technique of hoisting the variants into an ad hoc data structure and
using existing looping techniques works well sometimes. (I use it in other
parts of the system.) It's relatively easy to expand, even though it moves
interesting information ("I'm calling the <code>analyze_pe</code> method!") to
a place where tools have more trouble finding it. (I search for
<code>&gt;analyze_pe</code> when I want to find method calls.) You may have used something similar to define several parametric methods at <code>BEGIN</code> time. It's the same type of pattern, and while Perl 5 provides most of the tools necessary to allow this, it doesn't natively express this pattern well.</p>

<p>I could also change the transaction object's <code>add()</code> method to do
nothing when it receives an empty list of arguments. I like that in some ways,
but I don't like it in others. I've come down on the side of keeping its
invariant (it always takes only one scalar as an object) pure for now. If I
change it to take a list of updates, that might be the right time to reconsider
this.</p>

<p>What I notice in the code as it stands right now is that the individual
variables <code>$pe_update</code> and <code>$cash_yield_update</code> are
synthetic variables. They only exist to support the code as written; they're
not necessary for the algorithm. If I were to modify this code but only this code, I'd really rather write:</p>

<pre><code>{
    ADD_TXN_WITH( $self, analyze_pe,         $stock, $stock_txn    );
    ADD_TXN_WITH( $self, analyze_cash_yield, $stock, $analysis_txn );
}</code></pre>

<p>... though that syntax doesn't thrill me either. The clearest possibility I
see right now is:</p>

<pre><code>{
    $stock_txn-&gt;add(    SKIP unless $self-&gt;analyze_pe( $stock )         );
    $analysis_txn-&gt;add( SKIP unless $self-&gt;analyze_cash_yield( $stock ) );
}</code></pre>

<p>... where <code>SKIP</code> does some magic to move to the next statement,
not the next loop iteration. (I have some ideas how to write XS to make this
work, but that creepy yak needs a shave and some mouthwash.)</p>

<p>The second best option right now is adding a function or method as
indirection to encapsulate the synthetic code. I'd rather avoid synthetic code,
but at least it reduces the possibility of copy and paste bugs.</p>

<p>For now, with only two steps in this analysis, I'm leaving it as it is. Two
repetitions of something this similar set off my refactoring alarm, but I
resist the urge for refactorings this small until I see three instances of
near-duplicate code.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2012/02/03/a-practical-use-for-macros-in-perl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Decades-Old Technique to Improve Programming Languages</title>
		<link>http://www.modernperlbooks.com/mt/2012/01/a-decades-old-technique-to-improve-programming-languages.html</link>
		<comments>http://www.modernperlbooks.com/mt/2012/01/a-decades-old-technique-to-improve-programming-languages.html#comments</comments>
		<pubDate>Mon, 23 Jan 2012 20:22:23 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[lisp]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[perl]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=444eb064a286b9c0c7a44d340e73f101</guid>
		<description><![CDATA[I promised in Testing Your Templates to explain how to solve the problem of the divergence between testable, debuggable code in your host language and a big wad of logic in a template language. This problem is an example of...]]></description>
			<content:encoded><![CDATA[
        <p>I promised in <a
href="http://www.modernperlbooks.com/mt/2012/01/testing-your-templates-and-why-it-doesnt-always-work.html">Testing
Your Templates</a> to explain how to solve the problem of the divergence
between testable, debuggable code in your host language and a big wad of logic
in a template language.</p>

<p>This problem is an example of the pattern of Why Writing Your Own DSL is
More Difficult Than You Think. Certainly Template Toolkit is among the better
templating systems (I've written a couple myself), but it exhibits problems
endemic to the process. (Then again, so does PHP. Now multiply that by the fact
that some people use templating systems <em>written in PHP</em> and if you have
to lie down for a while before the feeling passes, please accept my
apologies.)</p>

<p>The semantics of Template Toolkit are great, when they work, but then
everything's great when it works the way you expect. Robust software handles
the cases you don't expect with aplomb, or at least without a boom.</p>

<p>A simple workaround for Template Toolkit is to avoid the fallback from potential method lookup to keyed hash access when dealing with an object. In other words, if <code>$blessed_hash-&gt;do_something()</code> fails, try <code>$blessed_hash-&gt;{do_something}</code>.</p>

<p>... except that that doesn't work when you want to call virtual methods on
unblessed references, such as calling methods on arrays or hashes.</p>

<p>Another option is to change the syntax such that calling a method is visibly different from accessing a member of an aggregate. Perl 5 does this. It works pretty well, in the sense that if you use the right operator (access element versus invoke method), you've expressed your intent in a visually unambiguous fashion).</p>

<p>... except that people complain about the Perl 5 dereferencing arrow quite a
bit. (Okay, you don't <em>need</em> an arrow to do this; as the <a
href="http://onyxneon.com/books/modern_perl/index.html">Modern Perl book</a>
explains, the postfix indexed access or postfix keyed operators of
<code>{}</code> and <code>[]</code> determine the type of operation
effectively.)</p>

<p>... and except that one of the design goals of Template Toolkit was to be
robust in the face of changing values provided to the template, such that it
provides a loosely coupled interface for the data it expects. That's a fine
goal, but it isn't free.</p>

<p>Here's the thing, though. The last time I looked, Template Toolkit compiles
templates into Perl 5 code as an optimization. (The last template system I
wrote did the same thing, but not as well. We should have used TT, but in our
defense, TT didn't exist then.) This transliteration/compilation stage must be
very, very cautious to allow standard Perl debugging and introspection tools to
treat this generated code correctly. That is to say, I don't want to debug a
big wad of generated code. I want to debug the code I actually wrote.</p>

<p>As usual, the solution is another layer of abstraction.</p>

<p>Perl 5 exists in two forms. The first is the source code you and I write.
The second is the optree which the Perl 5 VM executes. There's nothing in
between. You have one or the other. When your code runs, you have the optree,
and the optree has references to the relevant location in the source code it
came from, but the correspondence is often less useful than you might like.</p>

<p>While the generated code from Template Toolkit could include the correct
file and line positions from templates, that's again less useful than you might
like. (It's useful, but it doesn't solve every problem.)</p>

<p>If Perl 5 had instead an intermediate form separate from raw code and raw
optrees, something more suitable to introspection and manipulation, we could
produce tools which worked with this intermediate form to improve debugging,
introspection, and better code generation.</p>

<p>We could even <em>inject</em> new code to add features (fall back to
attribute access; prevent the fallback to attribute access) to code, even
within lexical scopes. That is to say, we could manipulate how libraries behave
from the outside in, and ensure that our changes would not leak out from our
desired scopes.</p>

<p>It's certainly possible to replace the Perl 5 opcodes yourself, if you're
comfortable reading Perl 5 source code, writing XS, relying on black magic, and
dealing with strange issues of thread safety and manipulating global or at
least interpreter-global values in a lexical fashion (while dealing with the
fact that <code>use</code> is recursive in a sense)&mdash;but isn't Perl about
<em>not</em> making people write C to do interesting things?</p>

<p>Certainly this isn't a technique you'd use every day, and it's not obviously
a way to make Perl 5 run faster (though many optimizations become much easier),
but the possibility for better abstraction and extension and correctness has
much to recommend it.</p>

<p>And, yes, Lisp demonstrated this idea <em>ages</em> ago.</p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2012/01/23/a-decades-old-technique-to-improve-programming-languages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>If We Could Resolve Predicates at Compile Time</title>
		<link>http://www.modernperlbooks.com/mt/2011/12/if-we-could-resolve-predicates-at-compile-time.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/12/if-we-could-resolve-predicates-at-compile-time.html#comments</comments>
		<pubDate>Mon, 12 Dec 2011 18:27:07 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[catalyst]]></category>
		<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[perl5]]></category>
		<category><![CDATA[typing]]></category>
		<category><![CDATA[webprogramming]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=4e36ac66b0108e9ced4978e017bbe995</guid>
		<description><![CDATA[The Catalyst web framework uses Perl 5 function attributes effectively&#38;mdash;I've seen few more effective uses of attributes. Any modern web framework has to deal with the idea of routes and request routing somehow. Given a request path (such as /stocks/AA/view_analysis),...]]></description>
			<content:encoded><![CDATA[
        <p>The <a href="http://catalystframework.org/">Catalyst web framework</a> uses
Perl 5 <a
href="http://perldoc.perl.org/perlsub.html#Subroutine-Attributes">function
attributes</a> effectively&mdash;I've seen few more effective uses of
attributes.</p>

<p>Any modern web framework has to deal with the idea of routes and request
routing somehow. Given a request path (such as <em>/stocks/AA/view_analysis</em>),
how does your application know what to do?</p>

<p>Catalyst solves this elegantly with a feature known as chained actions.
Controller methods can consume zero or more parts of the path but, when
explicitly chained, can combine. Consider the example request path. The
controller is <em>Stocks.pm</em>. The second component of the path
(<em>/AA</em>) is the identifier for a stock (<a
href="http://www.alcoa.com/global/en/home.asp">Alcoa</a>, to be specific. I'm
neither long nor short on Alcoa itself, though I probably own some shares as
part of a fund somewhere.) The final component of the path,
<em>/view_analysis</em>, is an action&mdash;a verb representing an action the
controller should take on the object representing Alcoa in the system.</p>

<p>You can probably start to see the idea of the chain right away.</p>

<p>The Stock controller has a controller method called <c>get_stock</c> which
grabs the stock symbol from the request path, looks it up in the database, and
stores the object representing that stock for further processing. If no such
symbol exists, it throws an exception.</p>

<p>The <code>view_analysis</code> method chains off of the <c>get_stock</c>
method such that Catalyst will only dispatch to <code>view_analysis</code> when
it's already successfully dispatched to <c>get_stock</c>. Unless you write a
custom dispatch system which bypasses the dispatch rules, users will never be
able to call <code>view_analysis</code> without a valid stock object
available.</p>

<p>(Further, these methods are part of a chain which requires that users have
successfully logged into the system; they chain off of a user authentication
system.)</p>

<p>In code terms, the relevant attributes look something like:</p>

<pre><code>sub authorized :Chained('/login/required') :PathPart('stocks') :CaptureArgs(0);

sub get_stock :Chained('authorized') :PathPart('') :CaptureArgs(1);

sub view_analysis :Chained('get_stock') :PathPart('view_analysis') :Args(0);</code></pre>

<p>The <code>:Chained</code> attribute is most relevant here.
<code>:PathPart</code> governs how Catalyst's dispatcher makes each method
visible to user requests (<code>get_stock</code> doesn't consume a part of the
path on its own, while <code>authorized</code> consumes the name of the
controller and <code>view_analysis</code> consumes its own name).
<code>:CaptureArgs</code> and <code>:Args</code> control how many other pieces
of the path the methods consume; in the case of <code>get_stock</code>, it's
the single path element between <code>/stocks</code> and any subsequent chained
actions&mdash;in this case, <code>/AA</code>. As <code>view_analysis</code> is
the end point of a chain, you use <code>:Args</code> instead of
<code>:CaptureArgs</code>.</p>

<p>With that all explained, request method chaining is fantastic. I can reuse
<code>get_stock()</code> for other request methods and get all of its benefits,
including the fact that only authorized users can even reach this point.</p>

<p>Yet I want to <em>prove</em> these characteristics of my application.</p>

<p>I want to prove these features so definitively that I don't want to write
tests for them. I want my program to fail to <em>compile</em> if these
characteristics are untrue.</p>

<p>I see chaining from <code>get_stock()</code> as supplying an invariant
precondition to <code>view_analysis()</code> such that it proves, to my
satisfaction, that I can always rely on a valid stock object being available
within the analysis method. Always. Similarly, I can always rely on a valid
user being available within both methods. Always always.</p>

<p>The problem comes in that it's easy to make a typo in the name of a chain or
a method, or to use <code>:CaptureArgs</code> instead of <code>:Args</code> or
vice versa.</p>

<p>Here's the thing: all of this metadata is metadata. All of this information
is available at compile time, before Perl has to execute anything.</p>

<p>If I had a really good and extensible type system in Perl 5, I could write a
couple of pieces of predicate logic to say that every chained method should be
a starting point or have a valid predecessor. These are trivial properties of
my program (no matter how large it gets) and they're resolvable with the
information available at the point of compilation. Even with complex controller
construction through the use of roles and parametric roles, this information is
available.</p>

<p>I know how to emulate this behavior by injecting some sort of
<code>CHECK</code> block into the code and schlepping through the symbol table
and inspecting attributes myself, but that's emulating a useful feature we
could exploit in a lot of ways.</p>

<p>Forget the talk about making Perl into Java or C++ by adding a silly
manifest static type system. We could find and fix real errors in
logic&mdash;trivial errors, trivially discoverable&mdash;if we had an
extensible type system which let us define our own simple predicates.</p>

<p>(Implementing such is left as an exercise for a small army of readers cloned
from a very small army of brilliant p5p hackers with copious spare time and a
habit of reading ACM papers before breakfast.)</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/12/12/if-we-could-resolve-predicates-at-compile-time/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Solving Problems or Absorbing Design Patterns</title>
		<link>http://www.modernperlbooks.com/mt/2011/11/solving-problems-or-absorbing-design-patterns.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/11/solving-problems-or-absorbing-design-patterns.html#comments</comments>
		<pubDate>Sat, 26 Nov 2011 19:29:19 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[cpan]]></category>
		<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[perl5]]></category>
		<category><![CDATA[perl6]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=2f08ecc187cd5d72c80f436d134e98b1</guid>
		<description><![CDATA[At the end of January I decided that Perl 6 is currently impractical for my purposes, but other people have different ideas. In any serious discussion of Perl 6, you'll find people claiming that Perl 6 is already usable. Discovering...]]></description>
			<content:encoded><![CDATA[
        <p>At the end of January <a href="http://www.modernperlbooks.com/mt/2011/08/why-my-side-project-doesnt-use-perl-6.html">I decided that Perl 6 is currently impractical for my purposes</a>, but other people have different ideas. In any serious discussion of Perl 6, you'll find <a href="http://perlmonks.org/?node_id=939875">people claiming that Perl 6 is already usable</a>.</p>

<p>Discovering <a
href="http://www.modernperlbooks.com/mt/2011/10/in-search-of-minimum-viable-utility.html">the
minimum viable utility of a programming language</a> is a difficult exercise.
Certainly in 1994 few people would have expected that the obvious successor to
Perl 4 would eventually need multi-megabytes of extensions to add a full object
system rivaling CLOS plus Smalltalk, an asynchronous event system, a
high-powered object-relational mapper with pervasive laziness, and an
abstraction mechanism for HTTP? Yet that's the state of the art in Perl in
2011, and we're all the better for it.</p>

<p>If you read carefully between the lines of my criticism of the current state
of every Perl 6 implementation I've used as well as what the people who claim
that "Perl 6 is usable right now" write, you may find that we approach the
problems we're trying to solve from two different angles. We even
<em>agree</em> on one of those vectors.</p>

<p>When someone like <a href="http://moritz.faui2k3.org/">Moritz Lenz</a>
writes "You can use Rakudo or Niecza for real programs now!", I think it's fair
to rephrase that as "Any of the leading Perl 6 implementations implements
enough structure of a complete and useful programming language that you can
implement your own code."</p>

<p>I can agree with this sentiment. I even go a step further; I don't mean to
water down his assertion or to put words in his mouth. If you analyze Perl 6
right now in terms of the <a href="http://dev.perl.org/perl6/rfc/">Perl 6
RFCs</a>, it's clear that Perl 6 even as currently implemented has advantages
over Perl 5 when you compare features on a matrix.</p>

<p>(I've since come to believe that <a
href="http://www.modernperlbooks.com/mt/2011/11/promoting-perls-features-versus-benefits.html">you're
dooming yourself to potential technical excellence and popular obscurity by
focusing on features instead of Getting Stuff Done</a>.)</p>

<p>To rephrase, Perl 6 may certainly be a better programming language than Perl
5 in that Perl 6 includes features Perl 5 should have had years ago. If design
patterns are signposts of missing language features, Perl 6 is the <a
href="http://c2.com/cgi/wiki?ChristopherAlexander">Christopher Alexander</a> of
programming.</p>

<p>If that's sufficient for your purposes, great. (You still have to deal with
performance issues and regressions, and licensing concerns with the Mono
dependency of Niecza (Niecza fans, be honest. How is my business supposed to
pay Novell anymore for indemnification per their patent licensing arrangement
with Microsoft&mdash;you remember, the Microsoft that sued TomTom for patent
infringement?), and the schism between Parrot and Rakudo on the Rakudo side, as
well as the history of Rakudo undergoing lengthy and repeated and
compatibility-busting rewrites of core components, but after eleven and a half
years, you ought to know you're an early adopter by now.  (Rakudo fans, be
honest. How long after nom became the main development branch did it take to
get all of the Panda modules passing tests again? Oh, they're still not?
QED.)</p>

<p>The other vector from which to approach problem solving in Perl says
something like "You know, if I'm already leaning heavily on the CPAN to
download Plack and an IMAP server and an OAuth implementation and AnyEvent and
several testing distributions, Moose really isn't that big a deal anymore." In
other words, maybe it is rather silly that in 2011 Perl 5 still doesn't have
much of an object system in the core and that it could really use real function
signatures, but the Perl community is awfully good at making the important
stuff on the CPAN just work, and Perl 5 without the CPAN is pretty anemic for
solving big important problems anyway, so grab perlbrew and fire up cpanm and
after you've finished your cup of tea, you're all set anyway.</p>

<p>The Python community has dealt with the same schism between Python 2.x and
Python 3.x, where Python 3 is arguably a better <em>language</em>, but only
superficial polyglot magpies and Usenet personas care solely and forever about
language qua language, and everyone else eventually needs to use a library or a
framework or a tool written by someone else.</p>

<p>I thought I wanted a better language to solve my problems, but as it turns
out, right now I can't have both, and I want to solve my problems more than I
want a better language. A good enough language which lets me solve my problems
is better than a great language in which I'm practically unproductive.</p>

<p>This is one of the few times when I agree both with the backwards
compatibility people <em>and</em> Python programmers. Mark your calendar.</p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/11/26/solving-problems-or-absorbing-design-patterns/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>In Search of Minimum Viable Utility</title>
		<link>http://www.modernperlbooks.com/mt/2011/10/in-search-of-minimum-viable-utility.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/10/in-search-of-minimum-viable-utility.html#comments</comments>
		<pubDate>Wed, 12 Oct 2011 18:55:44 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[advocacy]]></category>
		<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[perl5]]></category>
		<category><![CDATA[perl6]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=009d957b91b7a87bce764b51d93f23c2</guid>
		<description><![CDATA[I've spent most of 2011 focusing on my business. Sure, I write heaps of code, but I direct most of my attention to figuring out how I can build a sustainable business which produces value and wealth. Eric Ries's the...]]></description>
			<content:encoded><![CDATA[
        <p>I've spent most of 2011 focusing on my business. Sure, I write heaps of
code, but I direct most of my attention to figuring out how I can build a
sustainable business which produces value and wealth.</p>

<p>Eric Ries's <a
href="http://www.amazon.com/Lean-Startup-Entrepreneurs-Continuous-Innovation/dp/0307887898?tag=onyneopre-20">the
Lean Startup</a> contains a great deal of wisdom (and his <em>Build</em>
chapter is the best non-code metaphor for test-driven design that I have
encountered). In particular, he argues that the only way to figure out what
customers are willing to pay for is to try to sell them something. The best
predictor of why people will give you money is what people give you money
for.</p>

<p>Yet you're here to read about Perl and programming.</p>

<p>My rant a couple of months ago about <a
href="http://www.modernperlbooks.com/mt/2011/08/why-my-side-project-doesnt-use-perl-6.html">Why
My Side Project Doesn't Use Perl 6</a> came from deep frustration. After eleven
years of development and more than a year after the long-awaited Rakudo Star
("finally ready for early adopters!") release, it was incredibly frustrating to
discover that, even as someone with commit access to the entire Rakudo stack
from specs to tests to Parrot to NQP to PCT to Rakudo itself, the whole thing
just wasn't ready for me to use even in a simple side project.</p>

<p>The biggest users of Perl 6 (via Rakudo) code right now are, as far as I can
tell, Rakudo itself (via a stripped-down bootstrapping mechanism), a single
blog written in Perl 6, and <a href="http://rosettacode.org/">Rosetta Code</a>
chrestomathy examples.</p>

<p>Yet I'm not here to bury Perl 6.</p>

<p>I've spent some time writing JavaScript, and I can't understand why people
say there's a nice language in there despite its flaws. (In my mind, it's
mostly <em>decent</em>, despite its flaws.) I suppose that's like saying "Wow,
Python supports functional programming!" if you learned Java because Scheme was
too scary or "Ruby is basically Smalltalk!" if everything you know about object
systems comes from realizing that PHP continues to get it wrong.</p>

<p>I've been thinking about how, if <a
href="http://blogs.perl.org/users/rafael_garcia-suarez/2011/10/why-dart-is-not-the-language-of-the-future.html">Dart
is not the language of the future</a>, what the language of the future might
be, and what Larry says about evolution versus revolution.</p>

<p>Arc turned out not to be the language of the future either.</p>

<p>Gradual improvement is well and good, and it's starting to serve Perl 5
pretty well. The ability to shed cruft and mistakes and poor designs holding
back future improvements (a real metamodel! slimmer memory footprint! JIT! safe
exceptions! function signatures! multiple dispatch! safe sandboxing! cheaper
and easier parallelism! implementations on other backends!) is crucial.</p>

<p>Feedback makes that happen.</p>

<p>Sure, you can predict that a project which relentlessly focuses on one and
only one hot thing (Write a blog in 15 minutes! Manipulate DOM elements on the
client! Deploy a dynamic web page just as easily as writing HTML!) will have a
success, but real revolutionary success comes from <em>making</em> a new niche,
like web development in 1994.</p>

<p>As much as I'd like to argue that you can iterate your way to a revolution
through carefully gathering and considering real user feedback, I don't
<em>know</em> that that's the case.</p>

<p>I worry that once you release a programming language with minimum viable
utility, you ossify early decisions of design and implementation such that you
can't quite yank the floorboards out from underneath any users you have, lest
they stop being users and stop providing feedback.</p>

<p>Somehow you have to balance the desire to preserve an existing community
with the need to attract new members to the community, and that may be the
hardest problem in programming language development.</p>

<p>If you read <a
href="http://www.sidhe.org/~dan/blog/archives/000435.html">Dan's Parrot
post-mortem</a>, you see those two tensions. Parrot's two biggest technical
failings from the start were writing the wrong code and keeping it around. The
revolution of Pugs wasn't that Haskell is magic or that all Perl needs is the
superhuman effort of a superhero (though Audrey certainly gave it her best
shot), but that there is no substitute for working code.</p>

<p>Parrot doomed itself for a decade because there was no serious working Perl
6 implementation for <em>years</em>. (There were three half-hearted attempts,
each a rewrite of the previous.) Parrot lumbered along implementing things it
thought Perl 6 might probably need without getting real working feedback by
actually running Perl 6 code. (Dan's been out of Parrot longer than he was in
Parrot, and some of that wrong code is still around, because <a
href="http://www.modernperlbooks.com/mt/2011/08/no-policy-can-save-wrong-code.html">you
can't yank the foundation out from under people's houses</a> without some
structure and warning and planning.)</p>

<p>Yet I'm not here to praise or bury Parrot either.</p>

<p>If I'm right that <a
href="http://www.modernperlbooks.com/mt/2011/10/the-jfdi-theory-of-language-adoption.html">normal
people adopt languages to get stuff done</a>, you have to take a pragmatic
approach. Make something radically better at getting something revolutionary
done, and you have a chance.</p>

<p>(PHP <em>is</em> radically better at making simple web pages than just about
anything else, even though the language itself is just about the worst thing
imaginable. Similarly, Java is radically better than C++ because of garbage
collection and a break from the PDP-8 type system of C, and also it was cheaper
than Smalltalk, at least until Oracle bolts a coin slot onto the JVM.)</p>

<p>In conclusion, I don't know.</p>

<p>On paper, Perl 6 is a nicer Perl than Perl 5.</p>

<p>In practice, none of its implementations reach the Minimal Viable Utility
stage for me, a fairly normal and fairly positive early adopter. I don't know
if that's good or bad for Perl 6.</p>

<p>It's good in the sense that it gives Perl 6 freedom to experiment to find
its revolution. It increases the technical possibility that it won't fall into
the "Wow, that's all Python 3000?" or "Arc? Scheme with some renamed builtins?"
or "PHP 5 is the new PHP 6" or "That's all the better they could do with Go?"
or "17,000 lines to write 'Hello, world!' in Dart, and they misunderstand OO so
badly that they think Java interfaces are a good idea?" trap.</p>

<p>It's bad in the sense that I'm not sure that any of the big three Perl 6
users right now are representative of the kind of revolution Perl 6
needs&mdash;plus after eight years of trying to get something useful shipped,
it's hard to work up the motivation to donate even more time and effort toward
that always nebulous someday.</p>

<p>Sure, Pugs demonstrated that writing tests for the specifications was incredibly valuable. By no means should anyone diminish that.</p>

<p>Sure, Rakudo demonstrated that a serious implementation of Perl 6 on Parrot
helped focus both projects.</p>

<p>Yet ultimately, both Parrot 1.0 and Rakudo Star were more fizzle than
sizzle, and I think that's because neither one rose to the level where normal
people (for however you want to characterize the kind of people you'd consider
normal users) could do useful things.</p>

<p>I know, I <em>know</em> it's really difficult to start a revolution,
especially when you don't know where it will end up, but very especially when
you don't know what it will be. I know you want to give yourself all sorts of
escape hatches and valves to help guide your evolution into a
revolution....</p>

<p>... but at some point, I have to get work done, and if the shortest distance
between here and there is using a lesser tool and if I'm not sacrificing too
much future to do it, I have to hold back a tear and wish that Perl 5 had
native method signatures or multiple dispatch or malleable control flow with
continuations or macros.</p>

<p>(What about <a href="https://github.com/sorear/niecza">Niecza</a>? I really
shouldn't have to explain this, but IRC commentary on how I'm a bad person
cannot seem to get this right. In mathematical terms, the set of things which
are not promissory estoppel contains the opinions of everyone who isn't legal
counsel or a director at Microsoft opinion about how it's safe for my business
to use Mono. See also <a href="http://lwn.net/Articles/320737/">Microsoft Sues
TomTom</a>. If you live in a country without the threat of software patents, or
if your livelihood otherwise can't be threatened by the possibility of a
lawsuit against your <em>use</em> of a project in a way a known patent
aggressor with patents on fundamental technologies you use and threatening
indemnification agreements with now-defunct licensees doesn't like, good for
you. We take your well-intentioned legal advice under advisement.)</p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/10/12/in-search-of-minimum-viable-utility/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tolstoy, Emerson, Style, and Maintainability</title>
		<link>http://www.modernperlbooks.com/mt/2011/10/tolstoy-emerson-style-and-maintainability.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/10/tolstoy-emerson-style-and-maintainability.html#comments</comments>
		<pubDate>Mon, 03 Oct 2011 18:27:15 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[maintainability]]></category>
		<category><![CDATA[perl]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=1ba45fea042d6714deb2b39514b1355d</guid>
		<description><![CDATA[Happy families are all alike; every unhappy family is unhappy in its own way. &#38;mdash; Leo Tolstoy, Anna Karenina I've noticed that most folks who default to Perl tend to write Perl in a manner largely inconsistent with the next...]]></description>
			<content:encoded><![CDATA[
        <blockquote><em>Happy families are all alike; every unhappy family is unhappy
in its own way.</em></blockquote>

<p>&mdash; Leo Tolstoy, <em>Anna Karenina</em></p>

<blockquote><em>I've noticed that most folks who default to Perl tend to write
Perl in a manner largely inconsistent with the next guy's.</em></blockquote>

<p>&mdash; <a href="http://news.ycombinator.com/user?id=eropple">eropple</a>,
<a href="http://news.ycombinator.com/item?id=3067217">Hacker News discussion of
Puppet, Chef, Ruby, Python, and Perl</a></p>

<blockquote><em>A foolish consistency is the hobgoblin of little minds, adored
by little statesmen and philosophers and divines.... "Ah, so you shall be sure
to be misunderstood." &mdash; Is it so bad, then, to be misunderstood?
Pythagoras was misunderstood, and Socrates, and Jesus, and Luther, and
Copernicus, and Galileo, and Newton, and every pure and wise spirit that ever
took flesh. To be great is to be misunderstood.</em></blockquote>

<p>&mdash; Ralph Waldo Emerson, <em>Self-Reliance</em></p>

<p>I suspect, but cannot yet prove, that the internal consistency of a program
is an emergent property discovered through active development, maintenance,
feedback from real users, and the concomitant reframing of features and
refactoring of code.</p>

<p>I believe, from long and often painful experience, that every good program
is good in its own way, while bad programs are all alike.</p>

<p>I understand that I will understand my problem domain better as I learn more
by solving it in parts. (But I'm happy to borrow a well-tested implementation
of the All Points Shortest Path algorithm when it's obvious I have a graph
traversal problem.)</p>

<p>I laugh at the people who recoil in mock horror at the use of sigils and
variable declarations and the general principle of TIMTOWTDI, but encourage
everyone else to monkeypatch global classes to create their own parser-abusing
"internal DSLs".</p>

<p>Then again, the dominant criticism of Lisp seems to be "Look at all the
parentheses!" and not "Wow, you mean I have to learn the semantics of this
series of macros and their possible combinations before I can help maintain
this program?"</p>

<p>May we laud our languages and tools and ecosystems for the ways in which
they support our discovery and promotion of deep consistencies.</p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/10/03/tolstoy-emerson-style-and-maintainability/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Right to be Wrong</title>
		<link>http://www.modernperlbooks.com/mt/2011/09/the-right-to-be-wrong.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/09/the-right-to-be-wrong.html#comments</comments>
		<pubDate>Wed, 07 Sep 2011 17:40:10 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[philosophy]]></category>
		<category><![CDATA[projectmanagement]]></category>
		<category><![CDATA[softwaredevelopment]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=156d7953c307959286202b9e561628c8</guid>
		<description><![CDATA[Language design is hard work&#38;mdash;not only because consistency of vision is a laborious process, but because the only way to know what users will do with your language is to wait until users use your language to do things. I...]]></description>
			<content:encoded><![CDATA[
        <p>Language design is hard work&mdash;not only because consistency of vision is
a laborious process, but because the only way to know what users will do with your
language is to wait until users use your language to do things. I wrote several
questions for my friends to use in their book <a href="http://www.amazon.com/gp/product/0596515170?ie=UTF8&tag=onyneopre-20">Masterminds of
Programming</a>, and one question I recommended asking of every language
designer was "How do you plan for an uncertain future when the only thing you
know is that you'll want to change something you had wrong?"</p>

<p>I'm rushing one of my side projects to the point where a hand-picked group
of friends and family can use it for practical purposes because they're my
target customers, and I'm neither so charming nor dashing that they won't tell
me with brutal honesty what works, what doesn't work, and what I never should
have thought they'd do.</p>

<p>No plan survives first contact with the enemy.</p>

<p><a
href="http://www.modernperlbooks.com/mt/2009/06/the-value-of-a-pumpking.html">I
have tremendous respect for the brave release managers of Perl 5</a>, as  a
seemingly innocuous change could cause countless hours of work for thousands,
tens of thousands, or even hundreds of thousands of developers. (One time I
almost broke half of the CPAN myself.) The need to get everything right exerts
immeasurable pressure to not do anything wrong.</p>

<p>The difference between "doing it right" and "not doing it wrong" is a vast
abyss.</p>

<p>Consider: I extract a CPAN module from code I'm using. I make it more
generic and reusable. I polish it. I publish it. Then the first report I get
about it is "This would be great, if..." and that's a <em>great</em> thing. In
truth, that's an <em>expected</em> part of Perl culture. That's one reason CPAN
version numbers stay below the magical candy-flavored rainbow sparkle 1.0
threshold for so long (<a href="http://search.cpan.org/perldoc?POE">POE</a>
took ten years to reach 1.0, and it's by no means the only example): we want
the right to be wrong and to change what's wrong.</p>

<p>That's one reason the common answer to "How do I get a new feature into the
Perl 5 core?" is "Write it as a CPAN extension first." (That answer is, as
often as not wrong, but it's right for philosophical reasons and wrong for
merely pragmatic reasons, and the latter are at least solvable.)</p>

<p>That's one reason the <a
href="http://blog.moose.perl.org/2010/09/moose-backwards-compatibility-policy-and-practice.html">Moose
backwards compatibility policy</a> exists. When inventing new things that no
one has ever invented before, it's easy to get things only mostly right, and
it's impossible to know what's wrong without people using it and reporting on
what's difficult or impossible or ugly.</p>

<p>That's one reason Perl 6 language design and implementation has gone through
cycles of reinvention and foundering. Perl 5 gets a lot of things right
philosophically and very wrong practically. Where Perl 6 gets a lot of things
more right practically, the consistency of vision and design required
rearrangement of the middle layers of philosophy. Above all, <em>there's no
substitute for running code</em> to discover how a system actually works, if it
works at all.</p>

<p>That's one reason test-driven design and frequent, small, timeboxed
iterations are part of agile or lean or whatever buzzword name you want to slap
on the very practical, flexible, effective development process most of the
great developers I know use&mdash;not because that's the only way to write
great software, but because you can learn so much so quickly about what you
really need when you give yourself the right to be wrong with little
consequence.</p>

<p>I'm not praising the desire to rewrite willy-nilly, nor am I suggesting that
the right approach to supporting software is to leave users to read changelogs
and run their comprehensive test suites to decide whether and when to upgrade
to new versions where everything is a candidate for major changes. I'd also
never suggest that the right to be wrong is a substitute for careful thought
and design based on the best information you have at the moment. We're
professionals, after all, and we need to bring our best professionalism and
knowledge and talent and care to our work.</p>

<p>Yet I am suggesting that we work with incomplete
information&mdash;information that's <em>expensive</em> to gather in toto, if
that's even possible&mdash;and that we have to do our best in the face of those
limitations. Without the freedom to make little mistakes (however we apply that
to our projects), we limit our possibility to make big wonderfuls.</p>

<p>(Yes, the prompting for this piece came from attempting to moderate a very
frustrating discussion between two projects where one revels in its ability to
be wrong frequently and expensively while actively prohibiting the other to be
wrong even in small ways. Dependencies are <em>difficult</em>.)</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/09/07/the-right-to-be-wrong/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What&#8217;s with That Trailing Punctuation Anyway?</title>
		<link>http://www.modernperlbooks.com/mt/2011/09/whats-with-that-trailing-punctuation-anyway.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/09/whats-with-that-trailing-punctuation-anyway.html#comments</comments>
		<pubDate>Fri, 02 Sep 2011 18:09:17 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[parsing]]></category>
		<category><![CDATA[perl5]]></category>
		<category><![CDATA[perlcom]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=bbed07d497fea7f019acccb8421599cd</guid>
		<description><![CDATA[Tom Christiansen's What Wrong with sort and How to Fix It (blame me for the title) gathered a lot of necessary attention about the necessity of collation to sort data in various languages. It also sparked a small discussion about...]]></description>
			<content:encoded><![CDATA[
        <p>Tom Christiansen's <a
href="http://www.perl.com/pub/2011/08/whats-wrong-with-sort-and-how-to-fix-it.html">What
Wrong with <code>sort</code> and How to Fix It</a> (blame me for the title)
gathered a lot of necessary attention about the necessity of <a
href="http://en.wikipedia.org/wiki/Collating_sequence">collation</a> to sort
data in various languages.</p>

<p>It also sparked a small discussion about "What in the world does
<em>that</em> mean and why would you do that?" regarding a single line of Tom's
code:</p>

<pre><code>@sorted_lines = Unicode::Collate::-&gt;new-&gt;sort(@lines);</code></pre>

<p>In particular, a few people asked "Why would you write
<code>Unicode::Collate::</code>?" As with far too many grotty parts of Perl 5,
the answer is "To avoid bareword parsing ambiguity."</p>

<p>Ambiguity? Sure. <code>Unicode::Collate</code> is a bareword. Oh, it's clearly a class name, unless it's a function call.</p>

<p>A function call?</p>

<p>Sure. It could be a call to <code>Unicode::Collate()</code>. This is a form
of the same problem you get when making a dative (colloquially "indirect
object") method call:</p>

<pre><code># buggy code; do not use
my $object = create Some::Class; # buggy code; do not use</code></pre>

<p>That is to say, the <em>meaning</em> of this code can change depending on
what else the Perl 5 parser has seen when it compiles this code.</p>

<p>If you're interested in gory details and you don't mind reading heavily
macroized and partially documented accreted C code, look at the
<c>S_intuit_method</c> function in Perl 5's <em>toke.c</em>. The comments in
that code explain the heuristics for resolving barewords.</p>

<p>Appending the package separator (amusingly <code>'</code>; did you think I
wouldn't try it?) makes the class name obviously a class name and not a
function call. Ambiguity removed, at the cost of slightly more ugly code.</p>

<p>With that said, the ugliness bothers me such that I never use this syntax
even as I admit its advantages. Instead I rely on coding standards to avoid
potential ambiguity by using lowercase for method names. So far, I've been
fortunate&mdash;but I cannot blame someone once burned for avoiding the problem
at the parser level.</p>

<p>(A sigil to identify classes could fix this, as would a unique operator to
instantiate or look up classes. None of these solutions completely satisfy
me.)</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/09/02/whats-with-that-trailing-punctuation-anyway/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is an Array Anyway?</title>
		<link>http://www.modernperlbooks.com/mt/2011/08/what-is-an-array-anyway.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/08/what-is-an-array-anyway.html#comments</comments>
		<pubDate>Wed, 31 Aug 2011 17:21:48 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[haskell]]></category>
		<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[perl5]]></category>
		<category><![CDATA[perl6]]></category>
		<category><![CDATA[typing]]></category>

		<guid isPermaLink="false">http://perlblogs.com/?guid=d1afff616bb651f48898ce589ec6bed4</guid>
		<description><![CDATA[Suppose Perl 5.20 let you write: class IceCreamSundae; method add_toppings(Array @toppings) { ... } Ignore class and method. Concentrate on Array. What does that mean? You can easily assume that this method adds zero or more toppings to an ice...]]></description>
			<content:encoded><![CDATA[
        <p>Suppose Perl 5.20 let you write:</p>

<pre><code>class IceCreamSundae;

method add_toppings(Array @toppings)
{
    ...
}</code></pre>

<p>Ignore <code>class</code> and <code>method</code>. Concentrate on
<code>Array</code>. What does that <em>mean</em>?</p>

<p>You can easily assume that this method adds zero or more toppings to an ice
cream sundae. Again though, what does that <em>mean</em>?</p>

<p>Does the method access the <code>Array</code> as a queue? As a stack? As a
linked list? As a double-ended queue? With standard iteration? With indexed
iteration? Is it destructive? Does it hold references to the elements of the
array, thus increasing their lifespan with regard to garbage collection?</p>

<p>Sure, you can make cheap and easy type checking work in this case (it's a
big patch in Perl 5, but it's not an impossible patch), but what does this code
<em>mean</em>?</p>

<p>If we're going to use languages where we don't have to worry about the
precise layout of our data structures in memory (because C has the type system
of PDP-8 assembly language), we should aim for something more specific and
useful and denotative than "Everyone knows what an array is!"</p>

<p>Well-factored programs walk a tight balance between overspecifying their
interfaces, thus too-tightly coupling themselves to specific representations,
and launching architecture astronauts into space with the unuseful Gordian-knot
complexity of too much genericity.</p>

<p>... but <a href="http://jamesshore.com/Blog/PrimitiveObsession.html">it's
tempting to use the language's core primitives</a>, because <em>everyone knows
what an array means</em> even though no one knows exactly what you're doing
with it, which is really the important part of what a good type system can
specify.</p>

<p>(Yes, I've written Haskell code. I appreciate Hindley-Milner and consider
myself privileged to have corresponded with Dr. Milner about language design in
depth. That doesn't change the fact that I can write trivial mathematical code
in Haskell which looks obviously correct both to readers and the type checker
but which generates infinite loops due to simple arithmetic principles. If you
choose the <em>wrong</em> types, you will get the wrong behavior.)</p>

<p><a
href="http://www.modernperlbooks.com/mt/2011/06/meaning-mechanism-type-tyranny.html">Would
that our programming languages encouraged us to express the intention of code
rather than making vague promises about its structure.</a></p>
        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/08/31/what-is-an-array-anyway/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inside-Out Failure Injection</title>
		<link>http://www.modernperlbooks.com/mt/2011/07/inside-out-failure-injection.html</link>
		<comments>http://www.modernperlbooks.com/mt/2011/07/inside-out-failure-injection.html#comments</comments>
		<pubDate>Fri, 15 Jul 2011 18:58:04 +0000</pubDate>
		<dc:creator>chromatic</dc:creator>
				<category><![CDATA[catalyst]]></category>
		<category><![CDATA[languagedesign]]></category>
		<category><![CDATA[modernperl]]></category>
		<category><![CDATA[perl5]]></category>
		<category><![CDATA[scope]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.modernperlbooks.com/mt/2011/07/inside-out-failure-injection.html</guid>
		<description><![CDATA[While it's still true that lexical scope is the fundamental unit of encapsulation in Perl 5, dynamic scope is a powerful tool. Consider this snippet from a Catalyst application controller I wrote: sub activate :Chained('superget') :PathPart('activate') :Args(0) { my ($self,...]]></description>
			<content:encoded><![CDATA[
        <p>While it's still true that <a href="http://www.modernperlbooks.com/mt/2010/06/the-fundamental-unit-of-encapsulation.html">lexical scope is the fundamental unit of encapsulation</a> in Perl 5, dynamic scope is a powerful tool.</p>

<p>Consider this snippet from a <a href="http://catalystframework.org/">Catalyst application controller</a> I wrote:</p>

<pre><code>sub activate :Chained('superget') :PathPart('activate') :Args(0)
{
    my ($self, $c) = @_;
    my $proj       = $c-&gt;stash-&gt;{project};

    try
    {
        $proj-&gt;activate_project( $c-&gt;stash-&gt;{user} );
        $c-&gt;add_status( 'Activated project ' . $proj-&gt;project_name );
    }
    catch { $c-&gt;add_error( $_ ) };

    $self-&gt;redirect_to_action( $c, 'view', '', [ $proj-&gt;id ] );
}</code></pre>

<p>Ignore almost everything but the <a
href="http://search.cpan.org/perldoc?Try::Tiny">Try::Tiny</a> code (the
<code>try</code>/<code>catch</code> blocks). The dynamic scope of this
exception handling code means any exception thrown from either method called
from the <code>try</code> block or any other code they call, will result in the
activation of the <code>catch</code> block. Outside of those two blocks, any
exceptions are the responsibility of something else.</p>

<p>That's easy to understand, but take it a step further and think of this
dynamic scope as some sort of multiverse behavior. (If this metaphor doesn't
work, that's fine. It's how I think of it.) Within a delimited scope
representing <em>program flow</em>, not source code, the universe has
changed.</p>

<p>Exceptions aren't the only use for dynamic scope, and even dynamic scopes
offer the possibility for encapsulation.</p.

<p>I wrote some interesting code the other day while refactoring out
accumulated duplication and improving the test coverage of the controller. My
goal was to test the error handling if the activation failed. This presented a
design opportunity: how could I force a failure of the activation? As you can
see from the controller, the project object is already in the stash. I
<em>could</em> override Catalyst's dispatch mechanism or internals to create a
dummy project object which dies on activation. I could extract these controller
tests into tests which don't go through the web interface. I could even use an
environment variable to change the behavior of
<code>$project-&gt;activate</code> to throw an error.</p>

<p>Instead, I used an injected monkeypatch. The resulting test looks like:</p>

<pre><code>    test_result_override
    {
        $ua-&gt;get_ok( 'http://localhost/projects/2/activate',
            'failed activation' );
        $ua-&gt;content_contains( 'Activation failed',
            '... should contain error message' );
    } Project =&gt; activate_project =&gt; sub { die 'Activation failed' };</code></pre>

<p><code>$ua</code> is an instance of <a
href="http://search.cpan.org/perldoc?Test::WWW::Mechanize::Catalyst">Test::WWW::Mechanize::Catalyst</a>.</p>

<p>You can probably see where this is going. Within the block passed to
<code>test_result_override</code>, the <code>Project</code> object's
<code>activate_project</code> method is the function passed as the final
argument&mdash;a function which throws an exception.</p>

<p>The monkeypatch injector was likewise relatively easy to write:</p>

<pre><code>sub test_result_override(&@)
{
    my ($test, $class, $subname, $sub) = @_;

    no strict 'refs';

    my $ref = "Appname::Schema::Result::${class}::${subname}";
    local *{ $ref };
    *{ $ref } = $sub;

    $test-&gt;();
}</code></pre>

<p>The function prototype of <code>&@</code> tells the Perl 5 parser to treat
the block as a function reference. The rest of the code merely performs the
monkeypatching with <code>local</code> (so that the monkeypatch will go away
when this function returns, however it returns).</p>

<p>Once I knew what this code should do (I wrote the code which used it
<em>first</em>), it took two minutes to write, and maybe five minutes to use in
the other places in this controller I needed it. This isn't always the best
approach, but this sufficiently encapsulated monkeypatch injection is
sufficiently powerful and useful for helping ensure that my code behaves as I
intended.</p>

        
    ]]></content:encoded>
			<wfw:commentRss>http://perlblogs.com/2011/07/15/inside-out-failure-injection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

