<?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>Virtuous Code &#187; oop</title>
	<atom:link href="http://devblog.avdi.org/tag/oop/feed/" rel="self" type="application/rss+xml" />
	<link>http://devblog.avdi.org</link>
	<description>&#34;The three virtues of a programmer: laziness, impatience, and hubris&#34; -- Larry Wall</description>
	<lastBuildDate>Mon, 20 May 2013 11:45:49 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Decoration is best, except when it isn&#8217;t</title>
		<link>http://devblog.avdi.org/2012/01/31/decoration-is-best-except-when-it-isnt/</link>
		<comments>http://devblog.avdi.org/2012/01/31/decoration-is-best-except-when-it-isnt/#comments</comments>
		<pubDate>Tue, 31 Jan 2012 14:00:00 +0000</pubDate>
		<dc:creator>Avdi Grimm</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://avdi.org/devblog/?p=2002</guid>
		<description><![CDATA[I think by now we all know to prefer composition over inheritance. But in a language with a lot of options, what&#8217;s the best kind of composition to use? Composing an adventure Consider an adventure game, with objects representing player &#8230; <a href="http://devblog.avdi.org/2012/01/31/decoration-is-best-except-when-it-isnt/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I think by now we all know to <a href="http://en.wikipedia.org/wiki/Composition_over_inheritance">prefer composition over inheritance</a>. But in a language with a lot of options, what&#8217;s the best kind of composition to use? </p>
<div id="outline-container-1" class="outline-3">
<h3 id="sec-1">Composing an adventure</h3>
<div class="outline-text-3" id="text-1">
<p> Consider an adventure game, with objects representing player characters. </p>
<pre class="src src-ruby"><span class="org-keyword">class</span><span class="org-whitespace-space"> </span><span class="org-type">Character</span>
<span class="org-whitespace-space">  </span><span class="org-comment-delimiter">#</span><span class="org-whitespace-space"> </span><span class="org-comment">...</span>
<span class="org-keyword">end</span>
</pre>
<p> A <code>Character</code> can be described: </p>
<pre class="src src-ruby"><span class="org-keyword">class</span><span class="org-whitespace-space"> </span><span class="org-type">Character</span>
<span class="org-whitespace-space">  </span><span class="org-comment-delimiter">#</span><span class="org-whitespace-space"> </span><span class="org-comment">...</span>
<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">describe</span>
<span class="org-whitespace-space">    </span>puts<span class="org-whitespace-space"> </span><span class="org-string">"You</span><span class="org-whitespace-space"> </span><span class="org-string">are</span><span class="org-whitespace-space"> </span><span class="org-string">a</span><span class="org-whitespace-space"> </span><span class="org-string">dashing,</span><span class="org-whitespace-space"> </span><span class="org-string">rugged</span><span class="org-whitespace-space"> </span><span class="org-string">adventurer."</span>
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>
<span class="org-whitespace-space">  </span><span class="org-comment-delimiter">#</span><span class="org-whitespace-space"> </span><span class="org-comment">...</span>
<span class="org-keyword">end</span>
</pre>
<p> A <code>Character</code> can look, listen, and smell his environment: </p>
<pre class="src src-ruby"><span class="org-keyword">class</span><span class="org-whitespace-space"> </span><span class="org-type">Character</span>
<span class="org-whitespace-space">  </span><span class="org-comment-delimiter">#</span><span class="org-whitespace-space"> </span><span class="org-comment">...</span>
<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">look</span>
<span class="org-whitespace-space">    </span>list(<span class="org-string">"You</span><span class="org-whitespace-space"> </span><span class="org-string">can</span><span class="org-whitespace-space"> </span><span class="org-string">see"</span>,<span class="org-whitespace-space"> </span>[<span class="org-string">"a</span><span class="org-whitespace-space"> </span><span class="org-string">lightning</span><span class="org-whitespace-space"> </span><span class="org-string">bug"</span>,<span class="org-whitespace-space"> </span><span class="org-string">"a</span><span class="org-whitespace-space"> </span><span class="org-string">guttering</span><span class="org-whitespace-space"> </span><span class="org-string">candle"</span>])
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>

<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">listen</span>
<span class="org-whitespace-space">    </span>list(<span class="org-string">"You</span><span class="org-whitespace-space"> </span><span class="org-string">hear"</span>,<span class="org-whitespace-space"> </span>[<span class="org-string">"a</span><span class="org-whitespace-space"> </span><span class="org-string">distant</span><span class="org-whitespace-space"> </span><span class="org-string">waterfall"</span>])
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>

<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">smell</span>
<span class="org-whitespace-space">    </span>list(<span class="org-string">"You</span><span class="org-whitespace-space"> </span><span class="org-string">smell"</span>,<span class="org-whitespace-space"> </span>[<span class="org-string">"egg</span><span class="org-whitespace-space"> </span><span class="org-string">salad"</span>])
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>

<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">list</span>(prefix,<span class="org-whitespace-space"> </span>objects)
<span class="org-whitespace-space">    </span>objects.each<span class="org-whitespace-space"> </span><span class="org-keyword">do</span><span class="org-whitespace-space"> </span>|o|
<span class="org-whitespace-space">      </span>puts<span class="org-whitespace-space"> </span><span class="org-string">"</span><span class="org-variable-name">#{prefix}</span><span class="org-whitespace-space"> </span><span class="org-variable-name">#{o}</span><span class="org-string">."</span>
<span class="org-whitespace-space">    </span><span class="org-keyword">end</span>
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>
<span class="org-whitespace-space">  </span><span class="org-comment-delimiter">#</span><span class="org-whitespace-space"> </span><span class="org-comment">...</span>
<span class="org-keyword">end</span>
</pre>
<pre class="src src-ruby">require<span class="org-whitespace-space"> </span><span class="org-string">'./decoration-vs-extension'</span>
cohen<span class="org-whitespace-space"> </span>=<span class="org-whitespace-space"> </span><span class="org-type">Character</span>.new
cohen.describe
cohen.look
cohen.listen
</pre>
<pre class="example">
You are a dashing, rugged adventurer.
You can see a lightning bug.
You can see a guttering candle.
You hear a distant waterfall.
</pre>
<p> The character can also consult all of his senses at once: </p>
<pre class="src src-ruby"><span class="org-keyword">class</span><span class="org-whitespace-space"> </span><span class="org-type">Character</span>
<span class="org-whitespace-space">  </span><span class="org-comment-delimiter">#</span><span class="org-whitespace-space"> </span><span class="org-comment">...</span>
<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">observe</span>
<span class="org-whitespace-space">    </span>look
<span class="org-whitespace-space">    </span>listen
<span class="org-whitespace-space">    </span>smell
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>
<span class="org-whitespace-space">  </span><span class="org-comment-delimiter">#</span><span class="org-whitespace-space"> </span><span class="org-comment">...</span>
<span class="org-keyword">end</span>
</pre>
<pre class="src src-ruby">require<span class="org-whitespace-space"> </span><span class="org-string">'./decoration-vs-extension'</span>
cohen<span class="org-whitespace-space"> </span>=<span class="org-whitespace-space"> </span><span class="org-type">Character</span>.new
cohen.observe
</pre>
<pre class="example">
You can see a lightning bug.
You can see a guttering candle.
You hear a distant waterfall.
You smell egg salad.
</pre>
<p> Characters can have various effects conferred upon them by items, potions, etc. A simple example is a hat: </p>
<pre class="src src-ruby">require<span class="org-whitespace-space"> </span><span class="org-string">'delegate'</span>
<span class="org-keyword">class</span><span class="org-whitespace-space"> </span><span class="org-type">BowlerHatDecorator</span><span class="org-whitespace-space"> </span>&lt;<span class="org-whitespace-space"> </span><span class="org-type">SimpleDelegator</span>
<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">describe</span>
<span class="org-whitespace-space">    </span><span class="org-keyword">super</span>
<span class="org-whitespace-space">    </span>puts<span class="org-whitespace-space"> </span><span class="org-string">"A</span><span class="org-whitespace-space"> </span><span class="org-string">jaunty</span><span class="org-whitespace-space"> </span><span class="org-string">bowler</span><span class="org-whitespace-space"> </span><span class="org-string">cap</span><span class="org-whitespace-space"> </span><span class="org-string">sits</span><span class="org-whitespace-space"> </span><span class="org-string">atop</span><span class="org-whitespace-space"> </span><span class="org-string">your</span><span class="org-whitespace-space"> </span><span class="org-string">head."</span>
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>
<span class="org-keyword">end</span>
</pre>
<p> At each turn of the game, the <code>Character</code> object will be decorated with whatever effects are currently active, and then a user command will be performed: </p>
<pre class="src src-ruby">require<span class="org-whitespace-space"> </span><span class="org-string">'./decoration-vs-extension'</span>
cohen<span class="org-whitespace-space"> </span>=<span class="org-whitespace-space"> </span><span class="org-type">BowlerHatDecorator</span>.new(<span class="org-type">Character</span>.new)
cohen.describe
</pre>
<pre class="example">
You are a dashing, rugged adventurer.
A jaunty bowler cap sits atop your head.
</pre>
</p></div>
</p></div>
<div id="outline-container-2" class="outline-3">
<h3 id="sec-2">Seeing in the dark</h3>
<div class="outline-text-3" id="text-2">
<p> A more interesting effect is conferred by an infravision potion. It enables your character to see in the dark. </p>
<pre class="src src-ruby"><span class="org-keyword">class</span><span class="org-whitespace-space"> </span><span class="org-type">InfravisionPotionDecorator</span><span class="org-whitespace-space"> </span>&lt;<span class="org-whitespace-space"> </span><span class="org-type">SimpleDelegator</span>
<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">describe</span>
<span class="org-whitespace-space">    </span><span class="org-keyword">super</span>
<span class="org-whitespace-space">    </span>puts<span class="org-whitespace-space"> </span><span class="org-string">"Your</span><span class="org-whitespace-space"> </span><span class="org-string">eyes</span><span class="org-whitespace-space"> </span><span class="org-string">glow</span><span class="org-whitespace-space"> </span><span class="org-string">dull</span><span class="org-whitespace-space"> </span><span class="org-string">red."</span>
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>

<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">look</span>
<span class="org-whitespace-space">    </span><span class="org-keyword">super</span>
<span class="org-whitespace-space">    </span>look_infrared
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>

<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">look_infrared</span>
<span class="org-whitespace-space">    </span>list(<span class="org-string">"You</span><span class="org-whitespace-space"> </span><span class="org-string">can</span><span class="org-whitespace-space"> </span><span class="org-string">see"</span>,<span class="org-whitespace-space"> </span>[<span class="org-string">"the</span><span class="org-whitespace-space"> </span><span class="org-string">ravenous</span><span class="org-whitespace-space"> </span><span class="org-string">bugblatter</span><span class="org-whitespace-space"> </span><span class="org-string">beast</span><span class="org-whitespace-space"> </span><span class="org-string">of</span><span class="org-whitespace-space"> </span><span class="org-string">traal"</span>])
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>
<span class="org-keyword">end</span>
</pre>
<p> While the character is experiencing the effects of an <a href="http://nethack.wikia.com/wiki/Infravision">infravision</a> potion, his powers of observation increase: </p>
<pre class="src src-ruby">require<span class="org-whitespace-space"> </span><span class="org-string">'./decoration-vs-extension'</span>
cohen<span class="org-whitespace-space"> </span>=<span class="org-whitespace-space"> </span><span class="org-type">InfravisionPotionDecorator</span>.new(<span class="org-type">Character</span>.new)
cohen.describe
cohen.look
</pre>
<pre class="example">
You are a dashing, rugged adventurer.
Your eyes glow dull red.
You can see a lightning bug.
You can see a guttering candle.
You can see the ravenous bugblatter beast of traal.
</pre>
<p> There&#8217;s just one little problem that crops up when the <code>#observe</code> method is called. </p>
<pre class="src src-ruby">require<span class="org-whitespace-space"> </span><span class="org-string">'./decoration-vs-extension'</span>
cohen<span class="org-whitespace-space"> </span>=<span class="org-whitespace-space"> </span><span class="org-type">InfravisionPotionDecorator</span>.new(<span class="org-type">Character</span>.new)
cohen.observe
</pre>
<pre class="example">
You can see a lightning bug.
You can see a guttering candle.
You hear a distant waterfall.
You smell egg salad.
</pre>
<p> Hey, where&#8217;d that bugblatter beast go? </p>
<p> The <code>Character#observe</code> method calls <code>#look</code>&mdash;but since the wrapped object has no knowledge whatsoever of the <code>InfravisionPotionDecorator</code>, it calls the original definition of <code>#look</code>, not the one which also calls <code>#look_infrared</code>. </p>
<p> Now, granted, this flaw actually works out in our intrepid adventurer&#8217;s favor, since the ravenous bugblatter beast of Traal is so stupid it thinks that if you can&#8217;t see it, it can&#8217;t see you. But never mind that: it&#8217;s still a bug, and bugs must be blattered. </p>
</p></div>
</p></div>
<div id="outline-container-3" class="outline-3">
<h3 id="sec-3">A solution that&#8217;s all wet</h3>
<div class="outline-text-3" id="text-3">
<p> We could patch this flaw by overriding <code>#observe</code> as well in the decorator: </p>
<pre class="src src-ruby"><span class="org-keyword">class</span><span class="org-whitespace-space"> </span><span class="org-type">InfravisionPotionDecorator</span><span class="org-whitespace-space"> </span>&lt;<span class="org-whitespace-space"> </span><span class="org-type">SimpleDelegator</span>
<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">observe</span>
<span class="org-whitespace-space">    </span>look
<span class="org-whitespace-space">    </span>listen
<span class="org-whitespace-space">    </span>smell
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>
<span class="org-keyword">end</span>
</pre>
<p> Yuck! This is the exact same implementation as in <code>Character</code>, just copied and pasted so that the correct implementaiton of <code>#look</code> will be called. Clearly this is non-DRY. But even worse, we&#8217;ve introduced a nasty variety of <a href="http://blog.rubybestpractices.com/posts/gregory/056-issue-24-connascence.html">connascence</a>. Every time we introduces a new <code>Character</code> method which calls <code>#look</code>, we&#8217;ll have to cull through every single effect decorator which overrides <code>#look</code>, adding copy-and-pasted versions of the new method so that it doesn&#8217;t accidentally ignore the effect-wrapped version. Double yuck! </p>
</p></div>
</p></div>
<div id="outline-container-4" class="outline-3">
<h3 id="sec-4">Modules to the rescue</h3>
<div class="outline-text-3" id="text-4">
<p> In Ruby, there is an easy solution: extend the character with a module instead of a decorator. </p>
<pre class="src src-ruby"><span class="org-keyword">module</span><span class="org-whitespace-space"> </span><span class="org-type">InfravisionPotionModule</span>
<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">describe</span>
<span class="org-whitespace-space">    </span><span class="org-keyword">super</span>
<span class="org-whitespace-space">    </span>puts<span class="org-whitespace-space"> </span><span class="org-string">"Your</span><span class="org-whitespace-space"> </span><span class="org-string">eyes</span><span class="org-whitespace-space"> </span><span class="org-string">glow</span><span class="org-whitespace-space"> </span><span class="org-string">dull</span><span class="org-whitespace-space"> </span><span class="org-string">red."</span>
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>

<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">look</span>
<span class="org-whitespace-space">    </span><span class="org-keyword">super</span>
<span class="org-whitespace-space">    </span>look_infrared
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>

<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">look_infrared</span>
<span class="org-whitespace-space">    </span>list(<span class="org-string">"You</span><span class="org-whitespace-space"> </span><span class="org-string">can</span><span class="org-whitespace-space"> </span><span class="org-string">see"</span>,<span class="org-whitespace-space"> </span>[<span class="org-string">"the</span><span class="org-whitespace-space"> </span><span class="org-string">ravenous</span><span class="org-whitespace-space"> </span><span class="org-string">bugblatter</span><span class="org-whitespace-space"> </span><span class="org-string">beast</span><span class="org-whitespace-space"> </span><span class="org-string">of</span><span class="org-whitespace-space"> </span><span class="org-string">traal"</span>])
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>
<span class="org-keyword">end</span>
</pre>
<pre class="src src-ruby">require<span class="org-whitespace-space"> </span><span class="org-string">'./decoration-vs-extension'</span>
cohen<span class="org-whitespace-space"> </span>=<span class="org-whitespace-space"> </span><span class="org-type">Character</span>.new.extend(<span class="org-type">InfravisionPotionModule</span>)
cohen.observe
</pre>
<pre class="example">
You can see a lightning bug.
You can see a guttering candle.
You can see the ravenous bugblatter beast of traal.
You hear a distant waterfall.
You smell egg salad.
</pre>
<p> This time the overridden method is added directly to the object via its singleton class. So even the object&#8217;s own unmodified methods get the new infravision version of <code>#look</code>. </p>
<p> Sadly, by enabling him to see the monster we have sealed our protagonists&#8217;s fate. But at least we fixed the bug! </p>
</p></div>
</p></div>
<div id="outline-container-5" class="outline-3">
<h3 id="sec-5">Other solutions</h3>
<div class="outline-text-3" id="text-5">
<p> That&#8217;s not the only way to fix the problem. We might, for instance, decompose our <code>Character</code> into individual body parts, with separate attributes for <code>eyes</code>, <code>nose</code>, and <code>ears</code>. The <code>Character</code> could then delegate the individual senses to their respective organs: </p>
<pre class="src src-ruby">require<span class="org-whitespace-space"> </span><span class="org-string">'forwardable'</span>
<span class="org-keyword">class</span><span class="org-whitespace-space"> </span><span class="org-type">Character</span>
<span class="org-whitespace-space">  </span>extend<span class="org-whitespace-space"> </span><span class="org-type">Forwardable</span>

<span class="org-whitespace-space">  </span>attr_accessor<span class="org-whitespace-space"> </span><span class="org-constant">:eyes</span>
<span class="org-whitespace-space">  </span>attr_accessor<span class="org-whitespace-space"> </span><span class="org-constant">:ears</span>
<span class="org-whitespace-space">  </span>attr_accessor<span class="org-whitespace-space"> </span><span class="org-constant">:nose</span>

<span class="org-whitespace-space">  </span>def_delegator<span class="org-whitespace-space"> </span><span class="org-constant">:eyes</span>,<span class="org-whitespace-space"> </span><span class="org-constant">:look</span>
<span class="org-whitespace-space">  </span>def_delegator<span class="org-whitespace-space"> </span><span class="org-constant">:ears</span>,<span class="org-whitespace-space"> </span><span class="org-constant">:lisen</span>
<span class="org-whitespace-space">  </span>def_delegator<span class="org-whitespace-space"> </span><span class="org-constant">:nose</span>,<span class="org-whitespace-space"> </span><span class="org-constant">:smell</span>
<span class="org-keyword">end</span>
</pre>
<p> A potion of infravision might then replace the character&#8217;s eyes with infrared-enhanced ones: </p>
<pre class="src src-ruby"><span class="org-keyword">class</span><span class="org-whitespace-space"> </span><span class="org-type">InfravisionPotionDecorator</span><span class="org-whitespace-space"> </span>&lt;<span class="org-whitespace-space"> </span><span class="org-type">SimpleDelegator</span>
<span class="org-whitespace-space">  </span><span class="org-keyword">class</span><span class="org-whitespace-space"> </span><span class="org-type">EyesDecorator</span><span class="org-whitespace-space"> </span>&lt;<span class="org-whitespace-space"> </span><span class="org-type">SimpleDelegator</span>
<span class="org-whitespace-space">    </span><span class="org-comment-delimiter">#</span><span class="org-whitespace-space"> </span><span class="org-comment">...</span>
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>

<span class="org-whitespace-space">  </span><span class="org-keyword">def</span><span class="org-whitespace-space"> </span><span class="org-function-name">initialize</span>(character)
<span class="org-whitespace-space">    </span><span class="org-keyword">super</span>(character)
<span class="org-whitespace-space">    </span>character.eyes<span class="org-whitespace-space"> </span>=<span class="org-whitespace-space"> </span><span class="org-type">EyesDecorator</span>.new(character.eyes)
<span class="org-whitespace-space">  </span><span class="org-keyword">end</span>
<span class="org-keyword">end</span>
</pre>
<p> &hellip;but this is an awful lot of code and ceremony. It might make sense someday, but right now it feels like massive overkill. The module extension approach, by contrast, is only a small change from our original version. </p>
</p></div>
</p></div>
<div id="outline-container-6" class="outline-3">
<h3 id="sec-6">Are decorators overrated?</h3>
<div class="outline-text-3" id="text-6">
<p> So what can we learn from this? When composing objects, Is it always better to use module extension than decoration? </p>
<p> In a word, no. For one thing, decoration is a simpler structure to understand. Given object <code>A</code> wrapped in object <code>B</code> wrapped in object <code>C</code>, it&#8217;s easy to reason about how method calls will be handled. They&#8217;ll always go one-way: a method in object <code>A</code> will never reference a method in <code>B</code> or <code>C</code>.By contrast, method calls in a module-extended object can bounce around the inheritance heirarchy in unexpected ways. </p>
<p> A second consideration is that once you&#8217;ve extended an object with a module, its behavior is changed for <strong>all</strong> clients, including itself. You can&#8217;t interact with the &#8220;unadorned&#8221; object anymore. You might extend an object for your own purposes, then pass it to a third-party method which doesn&#8217;t understand the modified behavior of the object and barfs as a result. </p>
<p> Finally, there&#8217;s a performance penalty. While it varies from implementation to implementation, dynamically extending objects can slow down your code as a result of the method cache beign invalidated. Of course, as with all performance-related guidelines, be sure to profile before making any code changes based on this point. </p>
</p></div>
</p></div>
<div id="outline-container-7" class="outline-3">
<h3 id="sec-7">Conclusion</h3>
<div class="outline-text-3" id="text-7">
<p> Decoration and module extension are both viable ways to compose objects in Ruby. Which to use is not a simple black-or-white choice; it depends on the purpose of the composition.  </p>
<p> For applications where you want to adorn an object with some extra functionality, or modify how it presents itself, a decorator is probably the best bet. Decorators are great for creating Presenters, where we just want to change an object&#8217;s &#8220;face&#8221; in a specific context.  </p>
<p> On the other hand, when building up a composite object at runtime object out of individual &#8220;aspects&#8221; or &#8220;facets&#8221;, module extension may make more sense. Judicious use of module extension can lead to a kind of &#8220;emergent behavior&#8221; which is hard to replicate with decoration or delegation. </p>
<p> At least, this has been my experience. Got some experiences or opinions on decoration vs. module extension? Feel free to leave a note in the comments! </p>
</div></div>
]]></content:encoded>
			<wfw:commentRss>http://devblog.avdi.org/2012/01/31/decoration-is-best-except-when-it-isnt/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>End your OOP Confusion with the Design Pattern Classifier</title>
		<link>http://devblog.avdi.org/2011/12/22/design-pattern-classifier/</link>
		<comments>http://devblog.avdi.org/2011/12/22/design-pattern-classifier/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 14:00:44 +0000</pubDate>
		<dc:creator>Avdi Grimm</dc:creator>
				<category><![CDATA[Humor]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[oop]]></category>

		<guid isPermaLink="false">http://avdi.org/devblog/?p=1941</guid>
		<description><![CDATA[The Ruby community has seen a renaissance of interest in classic Object-Oriented thinking lately. We&#8217;re talking about Presenters, and DCI, and Data Objects. But with these new discussions come new problems. Namely: the dreaded pattern terminology debate. He says it&#8217;s a Decorator. &#8230; <a href="http://devblog.avdi.org/2011/12/22/design-pattern-classifier/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>The Ruby community has seen a renaissance of interest in classic Object-Oriented thinking lately. We&#8217;re talking about Presenters, and DCI, and Data Objects. But with these new discussions come new problems. Namely: the dreaded <em>pattern terminology debate</em>. He says it&#8217;s a Decorator. She says it&#8217;s an Adapter. Who is right?</p>
<p>Well fret no more, because I have devoted literally <em>tens of minutes</em> of effort to creating a solution to all of these nagging semantic questions. I give you: the <a href="http://avdi.org/classifier/">Design Pattern Classifier</a>. Give it a chunk of code, and it will tell you, to within 0.001 of a Dijkstra (the universal measurement unit of software correctness), the name of that pattern!</p>
<p>Enjoy, won&#8217;t you?</p>
]]></content:encoded>
			<wfw:commentRss>http://devblog.avdi.org/2011/12/22/design-pattern-classifier/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Object Oriented Programming Books</title>
		<link>http://devblog.avdi.org/2011/12/16/oop-books/</link>
		<comments>http://devblog.avdi.org/2011/12/16/oop-books/#comments</comments>
		<pubDate>Fri, 16 Dec 2011 17:28:00 +0000</pubDate>
		<dc:creator>Avdi Grimm</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[books]]></category>
		<category><![CDATA[oop]]></category>

		<guid isPermaLink="false">http://avdi.org/devblog/?p=1929</guid>
		<description><![CDATA[A few people have asked for recommendations of good foundational Object Oriented Programming texts. The truth is I&#8217;m kind of behind on my formal OOP reading, and some of the early texts I read I wouldn&#8217;t recommend. My first proper OOP book was &#8230; <a href="http://devblog.avdi.org/2011/12/16/oop-books/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>A few people have asked for recommendations of good foundational Object Oriented Programming texts. The truth is I&#8217;m kind of behind on my formal OOP reading, and some of the early texts I read I wouldn&#8217;t recommend. My first proper OOP book was <a href="http://www.amazon.com/Object-Oriented-Analysis-Design-Applications-3rd/dp/020189551X%3FSubscriptionId%3DAKIAIRXKO4LLU2ACVMRQ%26tag%3Dthlafa-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D020189551X">Object-Oriented Analysis and Design with Applications</a> by Booch, and while it&#8217;s not a <em>bad</em> book, I remember it being awfully dry.</p>
<p>Honestly, most of what I know I learned from surfing <a href="http://c2.com/cgi/wiki">WikiWiki</a>. It&#8217;s still the best source of collected software development thought on the planet, albeit not the most organized. I highly recommend killing an hour or hundred link-surfing WikiWiki.</p>
<p><a href="http://www.amazon.com/Object-Oriented-Software-Construction-Book-CD-ROM/dp/0136291554%3FSubscriptionId%3DAKIAIRXKO4LLU2ACVMRQ%26tag%3Dthlafa-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D0136291554"><img class="alignleft" src="http://ecx.images-amazon.com/images/I/51Zf1A3k-ZL._SL75_.jpg" alt="" width="57" height="75" /></a>I haven&#8217;t read all of it yet, but <a href="http://www.amazon.com/Object-Oriented-Software-Construction-Book-CD-ROM/dp/0136291554%3FSubscriptionId%3DAKIAIRXKO4LLU2ACVMRQ%26tag%3Dthlafa-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D0136291554">Object-Oriented Software Construction</a>, by Bertrand Meyer, is probably one of the better guides out there about how to think of the world in terms of objects with well-defined responsibilities.</p>
<p><a href="http://www.amazon.com/Smalltalk-Best-Practice-Patterns-Kent/dp/013476904X%3FSubscriptionId%3DAKIAIRXKO4LLU2ACVMRQ%26tag%3Dthlafa-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D013476904X"><img class="alignright" src="http://ecx.images-amazon.com/images/I/51T64R1B3RL._SL75_.jpg" alt="" width="57" height="75" /></a>I can wholeheartedly recommend Kent Beck&#8217;s <a href="http://www.amazon.com/Smalltalk-Best-Practice-Patterns-Kent/dp/013476904X%3FSubscriptionId%3DAKIAIRXKO4LLU2ACVMRQ%26tag%3Dthlafa-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D013476904X">Smalltalk Best Practice Patterns</a>. It masquerades as a book about Smalltalk, but it&#8217;s really a book about how to write clean OO code all the way down at the method level.</p>
<p><a href="http://www.amazon.com/Growing-Object-Oriented-Software-Guided-ebook/dp/B002TIOYVW%3FSubscriptionId%3DAKIAIRXKO4LLU2ACVMRQ%26tag%3Dthlafa-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB002TIOYVW"><img class="alignleft" src="http://ecx.images-amazon.com/images/I/51Ia3QYtb-L._SL75_.jpg" alt="" width="57" height="75" /></a>I have a long list of OO books I&#8217;ve been meaning to get to. I hear good things about both <a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215%3FSubscriptionId%3DAKIAIRXKO4LLU2ACVMRQ%26tag%3Dthlafa-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D0321125215">Domain-Driven Design</a> and <a href="http://www.amazon.com/Growing-Object-Oriented-Software-Guided-ebook/dp/B002TIOYVW%3FSubscriptionId%3DAKIAIRXKO4LLU2ACVMRQ%26tag%3Dthlafa-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB002TIOYVW">Growing Object-Oriented Software, Guided by Tests</a>. I&#8217;ve always wanted to read some of Rebecca Wirfs-Brock&#8217;s work, such as <a href="http://www.amazon.com/Object-Design-Roles-Responsibilities-Collaborations/dp/0201379430%3FSubscriptionId%3DAKIAIRXKO4LLU2ACVMRQ%26tag%3Dthlafa-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D0201379430">Object Design: Roles, Responsibilities, and Collaborations</a>, as well as Uncle Bob&#8217;s <a href="http://www.amazon.com/Software-Development-Principles-Patterns-Practices/dp/0135974445%3FSubscriptionId%3DAKIAIRXKO4LLU2ACVMRQ%26tag%3Dthlafa-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D0135974445">take on the subject</a>. Speaking of Uncle Bob, his Ruby Midwest keynote piqued my interest in Ivar Jacobson&#8217;s <a href="http://www.amazon.com/Object-Oriented-Software-Engineering-Approach/dp/0201544350%3FSubscriptionId%3DAKIAIRXKO4LLU2ACVMRQ%26tag%3Dthlafa-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D0201544350">book on use-case driven OOP</a>.</p>
<p>Obviously, this list is far from comprehensive. So I&#8217;d like to open the floor: what books do <em>you</em> consider essential first-level Object Oriented reading material?</p>
]]></content:encoded>
			<wfw:commentRss>http://devblog.avdi.org/2011/12/16/oop-books/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Early access beta of &#8220;Objects on Rails&#8221; Now Available</title>
		<link>http://devblog.avdi.org/2011/11/15/early-access-beta-of-objects-on-rails-now-available-2/</link>
		<comments>http://devblog.avdi.org/2011/11/15/early-access-beta-of-objects-on-rails-now-available-2/#comments</comments>
		<pubDate>Tue, 15 Nov 2011 19:38:03 +0000</pubDate>
		<dc:creator>Avdi Grimm</dc:creator>
				<category><![CDATA[Announcements]]></category>
		<category><![CDATA[Books]]></category>
		<category><![CDATA[books]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://avdi.org/devblog/?p=1916</guid>
		<description><![CDATA[UPDATE: Objects on Rails is now complete and freely available online. Often, at conferences and users group meetings, I find myself discussing the intersection of Ruby on Rails, Object-Oriented development, and Test-Driven Development, and I&#8217;ll mention something like &#8220;I prefer to develop my &#8230; <a href="http://devblog.avdi.org/2011/11/15/early-access-beta-of-objects-on-rails-now-available-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>UPDATE: Objects on Rails is now complete and <a href="http://objectsonrails.com/">freely available online</a>.</p>
<p>Often, at conferences and users group meetings, I find myself discussing the intersection of Ruby on Rails, Object-Oriented development, and Test-Driven Development, and I&#8217;ll mention something like &#8220;I prefer to develop my business objects first, and add ActiveRecord in later&#8221;. This usually leads to questions about how I structure my projects, how I isolate the business logic from ActiveRecord for testing, and so on. These discussions usually wind up with me saying &#8220;I&#8217;ll write a blog post about it&#8230;&#8221;.</p>
<p>A couple months ago I set out to start that blog post. I looked up from my keyboard a few hours later and realized that I had something rather larger than a blog post on my hands. Since then I&#8217;ve been pecking away at from time to time, in between work and conference travel. Now it&#8217;s reached the point where I&#8217;ve got a rough draft and it&#8217;s time to get some reader input.</p>
<p>When the book is complete I plan on releasing it <strong>for free</strong> for online reading in it&#8217;s entirety. It&#8217;s not quite ready for that stage yet. But today, <strong>I&#8217;m making an early-access (very) beta draft available for $5</strong>.</p>
<p>Wait a second&#8230; I&#8217;m selling you a book which I&#8217;ll eventually put online for free? How is that a good deal?</p>
<p>Here&#8217;s what you get for your money:</p>
<ul>
<li>Early access!</li>
<li>Input into the final product.</li>
<li>When they are ready, you&#8217;ll get <strong>PDF, Mobi, and Epub versions</strong> for your offline reading pleasure. These versions will not be made available for free.</li>
<li>Once it is ready, <strong>a copy of the full source code including revision history</strong> of the working demo project the book is based on. Again, this will not be made available for free.</li>
<li>A warm, fuzzy feeling because you&#8217;re supporting me in writing this and future books, like my upcoming &#8220;Confident Ruby&#8221;.</li>
</ul>
<div><span style="font-size: small;"><span class="Apple-style-span" style="line-height: 24px;">Curious about what&#8217;s in the book? Here are some of the topics covered:</span></span></div>
<div><span style="font-size: x-small;"><span class="Apple-style-span" style="line-height: 24px;"><br />
</span></span></div>
<ul>
<li>Starting with business models, adding persistence later.</li>
<li>Blazing-fast isolated tests using minitest without Rails loaded.</li>
<li>Using the language of the domain, not the language of the framework.</li>
<li>Stubbing out whole classes and modules in tests.</li>
<li>Stop worrying and learn to love Dependency Injection</li>
<li>Using the Presenter pattern to iron out convoluted view logic.</li>
<li>Exposing rich hypermedia RESTful resources with presenters.</li>
<li>Treating ActiveRecord as an implementation detail.</li>
<li>Separating fast unit tests from slower integration tests.</li>
<li>When to throw away your tests.</li>
<li>Using object composition to separate concerns.</li>
<li>Extracting object Roles into their own objects.</li>
</ul>
<p>Sound interesting? Click here to buy it now:</p>
<p style="text-align: center;"><a class="dpdcart iframe" href="https://getdpd.com/v2/cart/add/6855/27062/26612"><img class="aligncenter" style="border-style: initial; border-color: initial; border-width: 0px;" src="https://getdpd.com/images/buy_buttons/atc/solid3/buy-now_1-6_red.png" alt="Add to Cart" width="150" height="57" border="0" /></a></p>
<p style="text-align: left;">UPDATE: Want to submit feedback or discuss the book? I&#8217;ve created a Google Group for that purpose: <a href="https://groups.google.com/group/objects-on-rails">https://groups.google.com/group/objects-on-rails</a></p>
]]></content:encoded>
			<wfw:commentRss>http://devblog.avdi.org/2011/11/15/early-access-beta-of-objects-on-rails-now-available-2/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>You Can&#8217;t Subclass Integers in Ruby</title>
		<link>http://devblog.avdi.org/2011/08/17/you-cant-subclass-integers-in-ruby/</link>
		<comments>http://devblog.avdi.org/2011/08/17/you-cant-subclass-integers-in-ruby/#comments</comments>
		<pubDate>Wed, 17 Aug 2011 05:29:33 +0000</pubDate>
		<dc:creator>Avdi Grimm</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[classes]]></category>
		<category><![CDATA[integer]]></category>
		<category><![CDATA[numeric]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[subclass]]></category>

		<guid isPermaLink="false">http://avdi.org/devblog/?p=1564</guid>
		<description><![CDATA[This post is mainly just an excuse to test a Gist plugin for WordPress. Occasionally, you might think it would be handy to subclass Numeric types such as Integer. For instance, you might want to create a constrained integer which &#8230; <a href="http://devblog.avdi.org/2011/08/17/you-cant-subclass-integers-in-ruby/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>This post is mainly just an excuse to test a <a href="http://wordpress.org/extend/plugins/embed-github-gist/">Gist plugin</a> for WordPress.</p>
<p>Occasionally, you might think it would be handy to subclass Numeric types such as Integer. For instance, you might want to create a constrained integer which can only have certain values.</p>
<p>Ruby isn&#8217;t quite turtles all the way down, though: Numerics in Ruby are <em>immediates</em>, meaning that they don&#8217;t represent a heap-allocated object. Since you can&#8217;t allocate them, you can&#8217;t create a subclass and allocate instances of the subclass:</p>
<script src="https://gist.github.com/1124430.js"></script><noscript><pre><code class="language-ruby ruby">class MyInteger &lt; Fixnum
end

n = MyInteger.new(23)           # =&gt;
# ~&gt; -:4:in `&lt;main&gt;': undefined method `new' for MyInteger:Class (NoMethodError)

# Huh? Fine, I'll reimplement .new:
class MyInteger &lt; Fixnum
  def self.new(*args)
    object = allocate
    object.initialize(*args)
    object
  end
end

n = MyInteger.new(23)           # =&gt; 
# ~&gt; -:10:in `allocate': allocator undefined for MyInteger (TypeError)
# ~&gt; 	from -:10:in `new'
# ~&gt; 	from -:16:in `&lt;main&gt;'
</code></pre></noscript>
]]></content:encoded>
			<wfw:commentRss>http://devblog.avdi.org/2011/08/17/you-cant-subclass-integers-in-ruby/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Demeter: It&#8217;s not just a good idea. It&#8217;s the law.</title>
		<link>http://devblog.avdi.org/2011/07/05/demeter-its-not-just-a-good-idea-its-the-law/</link>
		<comments>http://devblog.avdi.org/2011/07/05/demeter-its-not-just-a-good-idea-its-the-law/#comments</comments>
		<pubDate>Tue, 05 Jul 2011 13:30:20 +0000</pubDate>
		<dc:creator>Avdi Grimm</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[bdd]]></category>
		<category><![CDATA[coupling]]></category>
		<category><![CDATA[demeter]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[law of demeter]]></category>
		<category><![CDATA[objects]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[structural coupling]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://avdi.org/devblog/?p=1357</guid>
		<description><![CDATA[Is #try really so bad? In response to my recent post about #try being a code smell, a lot of people made the reasonable objection that the example I used&#8212;of using #try on a a Hash&#8212;was a pathological case. A &#8230; <a href="http://devblog.avdi.org/2011/07/05/demeter-its-not-just-a-good-idea-its-the-law/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<h3>Is <code>#try</code> really so bad?</h3>
<p>In response to my recent <a href="http://avdi.org/devblog/2011/06/28/do-or-do-not-there-is-no-try/">post about <code>#try</code> being a code smell</a>, a lot of people made the reasonable objection that the example I used&#8212;of using <code>#try</code> on a a Hash&#8212;was a pathological case. A much more typical usage of <code>#try</code> looks like this:</p>
<pre name="code" class="ruby">
def user_info(user)
  "Name: #{user.name}. Dept: #{user.department.try(:name)}"
end
</pre>
<p><code>user</code> may or may not have an associated department, so the call to <code>Department#name</code> is wrapped in a <code>#try</code>. If there is an associated department, its name will be returned. If not, the result will be <code>nil</code>.</p>
<p>Straightforward enough. Is there anything wrong with this code?</p>
<p>I can think of a a few things. For one thing, it&#8217;s ugly. For my money, one of the hallmarks of beautiful code is that it&#8217;s visually consistent: similar operations have similar appearance. In the code above, we access one attribute with simple dot syntax (<code>.name</code>), and another with a very different-looking <code>.try(:name)</code>, even though in both cases the concept we are trying to express is the same: &#8220;get the &#8216;name&#8217; attribute&#8221;.</p>
<p>It&#8217;s a variety of ugliness that tends to proliferate, too. Starting with the code above, it&#8217;s not a very big leap to get to this:</p>
<pre name="code" class="ruby">
def user_info(user)
  "Name: #{user.name}. Boss: #{user.department.try(:head).try(:name)}"
end
</pre>
<p>Yuck.</p>
<p>And then there are the tests. They&#8217;ll probably look something like this:</p>
<pre name="code" class="ruby">
describe '#user_info' do
  subject { user_info(user) }
  let(:user) { stub('user', :name => "Bob", :department => stub(:name => "Accounting")) }
  specify {
    subject.should match(/Dept: Accounting/)
  }
end
</pre>
<h3>Metastasizing mocks</h3>
<p>This, again, doesn&#8217;t seem so bad. But give that test suite six months of active development, and chances are the tests wind up looking more like this:</p>
<pre name="code" class="ruby">
describe '#user_info' do
  subject { user_info(user) }
  let(:user) { 
    stub('user', 
         :name => "Bob", 
         :department => 
           stub(:name     => "Accounting",
                :head     => 
                  stub(:name     => "Jack", 
                       :position => stub(:title => "Vice President"))),
            :division => stub(:name => "Microwave Oven Programming")),
          :position => stub(:title => "Senior Bean Counter"))
 }
  # examples...
end
</pre>
<p>Not only that, the same tree of stubs will probably be duplicated, with subtle differences, for every test group that interacts with a User&#8212;because no one has time to sort out the specific subset of stubs that a given test actually <em>needs</em> in order to function.</p>
<p>At some point the client will decide that users really need to be associated with zero or more departments instead of just one. At that point some unlucky programmer will spend a late night fixing the 300 tests this &#8220;small change&#8221; breaks because of all the stubs that model the old behavior. Then the next day he&#8217;ll write an angry rant about how mock objects are a bad idea.</p>
<h3>Structural coupling</h3>
<p>The seed of this all-too-common predicament is <em>structural coupling</em>. What&#8217;s structural coupling? To define it, let&#8217;s start with a review of the DRY principle:</p>
<blockquote><p>Every piece of knowledge must have a single, unambiguous, authoritative representation within the system.</p></blockquote>
<p>It&#8217;s easy to think about DRYness just in terms of data: e.g., there should be only one place in the system for API keys; they shouldn&#8217;t just be copy-and-pasted willy-nilly throughout the codebase. But DRY applies equally to <em>structural knowledge</em>: knowledge about the composition of and relationships between your objects.</p>
<p>Let&#8217;s take a look at the code we started out with:</p>
<pre name="code" class="ruby">
def user_info(user)
  "Name: #{user.name}. Dept: #{user.department.try(:name)}"
end
</pre>
<p>This seemingly innocuous code makes the following assumptions:</p>
<ul>
<li><code>user</code> will have a name property.</li>
<li><code>user</code> may or may not have a single department.</li>
<li><code>user</code>&#8216;s department, in turn, has a name property</li>
</ul>
<p>By going two levels deep into <code>user</code>&#8216;s associations, we&#8217;ve made a <em>structural coupling</em> between this code and the models it works with. We&#8217;ve duplicated knowledge about a User&#8217;s associations&#8212;canonically located in the User and Department classes&#8212;in the <code>#user_info</code> method.</p>
<p>And the <code>#try</code> method was an enabler. By papering over the ugly <code>user.department &#038;&#038; user.department.name</code> construct we&#8217;d otherwise have had to use, <code>#try</code> made the coupling an easier syntactical pill to swallow.</p>
<p>This would be bad enough if we made a habit of it, because we&#8217;d have to change every method with a similar structural coupling whenever the innards of User or Department changed. But because we&#8217;re good Test-Driven developers, we then proceeded to couple <em>dozens</em> of test suites to a specific model structure, in the form of stubs and mock objects.</p>
<p>This is clearly an undesirable outcome. Wouldn&#8217;t it be handy to have a simple rule that helps us avoid structural coupling?</p>
<h3>The Law of Demeter</h3>
<p>Back in the 1980s, a group of programmers working on a project called the Demeter system realized that certain qualities in their object-oriented code led to the code being easier to maintain and change. Qualities such as low coupling; information hiding; localization of information, and narrow interfaces between objects. They asked themselves: &#8220;Is there a <em>simple</em> heuristic that humans <em>or</em> machines can apply to code to determine whether it has these positive qualities?&#8221;.</p>
<p>The answer they came up with came to be known as the &#8220;Law of Demeter&#8221;. It is stated as follows:</p>
<blockquote><p>
For all classes C. and for all methods M attached to C, all objects to which M sends a message must be instances of classes associated with the following classes:</p>
<ol>
<li>The argument classes of M (including C).</li>
<li>The instance variable classes of C.</li>
</ol>
<p>(Objects created by M, or by functions or methods which M calls, and objects in global variables are considered as arguments of M.)
</p></blockquote>
<p><a href="http://c2.com/cgi/wiki?LawOfDemeter">WikiWiki explains the law</a> like this:</p>
<ul>
<li>Your method can call other methods in its class directly.</li>
<li>Your method can call methods on its own fields directly (but not on the fields&#8217; fields).</li>
<li>When your method takes parameters, your method can call methods on those parameters directly.</li>
<li>When your method creates local objects, that method can call methods on the local objects.</li>
</ul>
<p>If that still seems confusing, here&#8217;s an alternative explanation from Peter Van Rooijen:</p>
<ul>
<li> You can play with yourself.</li>
<li> You can play with your own toys (but you can&#8217;t take them apart),</li>
<li> You can play with toys that were given to you.</li>
<li> And you can play with toys you&#8217;ve made yourself.</li>
</ul>
<p>The Demeter programmers wrote up their experiences in a paper called <a href="http://www.ccs.neu.edu/research/demeter/papers/law-of-demeter/oopsla88-law-of-demeter.pdf"><cite>Object-Oriented Programming: An Objective Sense of Style</cite></a>. What they found was that when methods were written in a form which complied with the Law of Demeter, the resulting codebase was easier to maintain and evolve.</p>
<p>It&#8217;s important to understand that the Law of Demeter is a <em>heuristic</em>, not an end in and of itself. It is not a law in the sense that you &#8220;must&#8221; write your code in a certain way. Rather, it is a law in the sense that it has been consistently observed that if code complies with the Law of Demeter, it almost certainly has a number of the qualities&#8212;encapsulation, loose coupling, etc.&#8212;desirable in an OO system.</p>
<h3>Laying down the law</h3>
<p>With that in mind, let&#8217;s take one more look at our example code:</p>
<pre name="code" class="ruby">
def user_info(user)
  "Name: #{user.name}. Dept: #{user.department.try(:name)}"
end
</pre>
<p>This code does not comply with the Law of Demeter. In addition to calling methods on its parameter, <code>user</code>, it also calls a method on the <em>result</em> of one of those methods: (<code>department.name</code>).</p>
<p>Assuming this is a Rails program, it is extremely easy to change the code to satisfy the law. First, we make a one-line addition to the User class:</p>
<pre name="code" class="ruby">
class User
  delegate :name, :to => :department, :prefix => true, :allow_nil => true
  # ...
end
</pre>
<p>The <a href="http://api.rubyonrails.org/classes/Module.html#method-i-delegate"><code>#delegate</code></a> macro, provided by ActiveSupport, generates a new method <code>User#department_name</code> which delegates to the user&#8217;s <code>#department</code>. By supplying <code>:allow_nil => true</code>, we ensure that the method will simply return nil in the case when there is no department associated with the user.</p>
<p>Here&#8217;s our code again, updated to use the new method:</p>
<pre name="code" class="ruby">
def user_info(user)
  "Name: #{user.name}. Dept: #{user.department_name}"
end
</pre>
<p>The code now respects the Law of Demeter: it is coupled only to the immediate interface of the <code>user</code> parameter.</p>
<p>The updated test suite now has only one stub object:</p>
<pre name="code" class="ruby">
describe '#user_info' do
  subject { user_info(user) }
  let(:user) { stub('user', :name => "Bob", :department_name => "Accounting") }
  specify {
    subject.should match(/Dept: Accounting/)
  }
end
</pre>
<p>Already we have a simpler test suite. But the real benefit comes when it is time to change the models. Let&#8217;s consider the case when a User changes from being linked to just one department, to having a list of zero or more departments. How we re-implement <code>User#department_name</code> depends on the needs of the domain. Let&#8217;s say the department name should now be a comma-separated list:</p>
<pre name="code" class="ruby">
class User
  def department_name
    departments.join(", ")
  end
end
</pre>
<p>We replace our delegate method with a method implementing the new semantics. And that&#8217;s the only change! The <code>#user_info</code> method remains the same, as does every test suite that references <code>User#departmentname</code>.</p>
<p>By adhering to the Law of Demeter, we have decreased coupling, and increased the velocity with which we can make changes to the business logic.</p>
<h3>Objection #1: What about method chains?</h3>
<p>&#8220;But Avdi&#8221; you may object, &#8220;it sounds like a good guideline, but clearly it&#8217;s not something to be rigidly adhered to in Ruby code. If we followed it all the time we could never do method chaining!&#8221;</p>
<p>Method chains are a core Ruby idiom, to be sure. As an example, here&#8217;s a method which takes a string and generates a &#8220;slug&#8221; for use as an identifier or as a a URL component:</p>
<pre name="code" class="ruby">
def slug(string)
  string.strip.downcase.tr_s('^[a-z0-9]', '-')
end
</pre>
<p>That&#8217;s one, two, three levels of method call. That can&#8217;t comply with the Law of Demeter, but it surely is concise and convenient!</p>
<p>Look again at the definition of the Law: it never says anything about the number of methods called, or the number of objects a method uses. It is strictly concerned with the number of <em>types</em> a method deals with.</p>
<p>The <code>#slug</code> method expects a String, and calls three methods, each one returning&#8230; another String. In fact, because it only calls methods for the type of object (String) passed into it as parameters, we find that this method complies perfectly with the Law of Demeter.</p>
<p>Likewise with another common Ruby pattern, chains of Enumerable methods like <code>#map</code> and <code>#select</code>. Because each returns another Enumerable object, there is no violation.</p>
<h3>Objection #2: Delegation explosion</h3>
<p>Another objection to Demeter is that strictly following it results in objects which are full of attributes which aren&#8217;t a direct part of their responsibility. Quoting Mark Wilden in the comments on my previous article:</p>
<blockquote><p>
Why should a Human have to know whether a Country has a name? Or any other attribute (unless it needs them itself)? If a Human is associated with multiple Countries (birth, residence, voting, vacation, etc.) does it then have to duplicate this delegation for each method of each country?</p>
<p>What about attributes that clearly have nothing to do with Human? Yes, one might say that a Human has a country_name. But does a Human have a country_population? A country_mortality_rate? I would say it does not, but Demeter insists that it must.
</p></blockquote>
<p>In the Object-Oriented view of the world, objects are not merely bags of attributes. They are entities to which you send messages and from which you receive replies. The classic example is a financial transaction: if I am a shopkeeper and you buy something from me, I don&#8217;t ask you for your wallet, rummage around until I find a credit card, and then copy down the information I need. Instead, I ask you for your credit card number and expiration date.</p>
<p>Putting this in object terms, a payment system which calls <code>person.wallet.credit_cards.first.number</code> exhibits tight structural coupling, and is closer in spirit to the data-structure-oriented programming which preceded OO. From an objects-sending-messages standpoint, it is perfectly reasonable for a Person to have a creditcard_number.</p>
<p>An important and often neglected point to hit on, before we move on: in an Object-Oriented system, it is prfectly allowable (and even encouraged) for objects to have <em>personas</em> or <em>facets</em>. A doctor deals with a patient&#8217;s physical symptoms while the reception desk deals with her wallet and insurance info. You wouldn&#8217;t walk into a doctor&#8217;s office, step up to the receptionist, and take off your shirt (unless you were on very good terms with the receptionist!).</p>
<p>Likewise, an object can have a large API, but only expose subsets of that API to different collaborators. Some languages enforce these subset relationships quite strictly; e.g. C++ with its private inheritance, and interfaces in Java. In other languages, such as Ruby, the restriction may be more about convention than something the language enforces. There&#8217;s nothing wrong with having a large API, so long as individual collaborators only talk to well-defined subsets of it.</p>
<p>But what about Mark&#8217;s example <code>human.country_mortality_rate</code>? Surely that&#8217;s pushing it a bit far?</p>
<p>Perhaps it is. But Demeter doesn&#8217;t prevent us from interacting with an objects second- and third-order associations; it simply asserts that we can&#8217;t interact with all of those objects <em>in the same method</em>. Look again at the formulation of the law:<br />
<blockquote>&#8230;all objects to which M sends a message&#8230;</p></blockquote>
<p> Demeter is a rule about methods <em>only</em>; it does not limit the set of types a <em>class</em> can interact with.</p>
<p>So this is perfectly legal:</p>
<pre name="code" class="ruby">
class StatPresenter
  def human_stats(human)
    "Age: #{human.age}.nCountry stats:n#{country_stats(human.country)}"
  end

  def country_stats(country)
    "  Mortality rate: #{country.mortality_rate}"
  end
end
</pre>
<p>Of course, you could completely violate the <em>spirit</em> of Demeter by taking this too far; something the authors of the Demeter paper note. Realistically, we&#8217;d probably want to break that <code>StatPresenter</code> class up into smaller classes once it started interacting with many different types of object.</p>
<p>The important thing, from the standpoint of Demeter, is to avoid tying a <em>single method</em> to a deep hierarchy of types, as well as limiting the <em>number</em> of types one method deals with.</p>
<p>One of the most basic ways we can limit the number of types a given method must be aware of is to eliminate the common case of &#8220;maybe nil&#8221; parameters. Remember, <code>NilClass</code> is a type too, and when a parameter might be nil we&#8217;ve increased the number of types the method has to know about by one. </p>
<p>As an example, the following version of the code above, while technically Demeter-compliant, is once again riddled with <code>#try</code> calls:</p>
<pre name="code" class="ruby">
class StatPresenter
  def human_stats(human)
    "Age: #{human.age}.nCountry stats:n#{country_stats(human.country)}"
  end

  def country_stats(country) # country may be nil
    "  Population: #{country.try(:population)}n" +
    "  Mortality rate: #{country.try(:mortality_rate)}n"
  end
end
</pre>
<p>The set of types <code>#country_stats</code> deals directly with is: <code>StatPresenter</code> (self), <code>Country</code>, and <code>NilClass</code>.</p>
<p>We can&#8217;t always get rid of switching on <code>nil</code> entirely, but what Demeter-influenced code gives us the opportunity to do is to easily confine that switch to a single location. Let&#8217;s rewrite the code above:</p>
<pre name="code" class="ruby">
class StatPresenter
  def human_stats(human)
    "Age: #{human.age}." + (human.country ? 
      "nCountry stats:n#{country_stats(human.country)}" :
      "n(No Country Stats)")
  end

  def country_stats(country)
    "  Population: #{country.population}n" +
    "  Mortality rate: #{country.mortality_rate)n"
  end
end
</pre>
<p>With this final edit, we&#8217;ve reduced the coupling of each method to a minimal point. <code>StatPresenter#human_stats</code> deals only with <code>Human</code> objects, and all it knows about <code>#country</code> is that it may or may not be there. <code>StatPresenter#human_stats</code> only knows about <code>Country</code> objects.</p>
<h3>Bringing Demeter to work</h3>
<p>&#8220;OK, fine. I can see that the Law of Demeter is a great guideline, at least in theory. But who has time to do all that refactoring? I have deadlines to meet!&#8221;</p>
<p>While refactoring code to comply with Demeter can certainly improve its design, I don&#8217;t think Demeter becomes truly practical until you incorporate it consistently into your coding style. Like many low-level &#8220;code construction&#8221; techniques&#8212;such as good variable naming&#8212;its value lies less in coming in and applying it after the fact, and more in practicing it until it becomes second nature.</p>
<p>Let&#8217;s take a look at how we&#8217;d add the department name to the <code>#user_info</code> method using TDD and the Law of Demeter. Here&#8217;s the code before adding the new functionality:</p>
<pre name="code" class="ruby">
def user_info(user)
  "Name: #{user.name}"
end
</pre>
<p>Now let&#8217;s add the department name.</p>
<ol>
<li>
<p>We write our test first:</p>
<pre name="code" class="ruby">
describe '#user_info' do
  subject { user_info(user) }
  let(:user) { stub('user', :name => "Bob", :department_name => "Accounting") }
  specify {
    subject.should match(/Dept: Accounting/)
  }
end
</pre>
<p>We know that nested mock/stub objects is a smell indicating structural coupling, so we force ourselves to write a  stub for the <code>user</code> object we <em>wish</em> we had. The <code>User#department_name</code> method doesn&#8217;t exist yet; we make a mental note to implement it. If we forget, the omission will be caught by our acceptance and/or integration tests.</p>
</li>
<li>We run the spec. It fails, because we haven&#8217;t implemented it yet</li>
<li>
<p> We write enough code to make the test pass:</p>
<pre name="code" class="ruby">
def user_info(user)
  "Name: #{user.name}. Dept: #{user.department_name}"
end
</pre>
</li>
<li>We run the tests again, and this time they pass.</li>
<li>
<p>The final step is to implement the <code>User#department_name</code> method. We could write a test asserting that the method delegates to <code>Department</code>; personally, I find this a little redundant and would just write the delegation and call it done:</p>
<pre name="code" class="ruby">
class User
  delegate :name, :to => :department, :prefix => true, :allow_nil => true
  # ...
end
</pre>
</li>
</ol>
<p>Revisiting your code to make it Demeter-compliant after the fact will indeed slow you down. By incorporating the rule into your habits, to the point that it becomes second nature, you reduce the impact (if any) to the point where it becomes insignificant. This is especially true in Ruby and Rails, where techniques such as composition-and-delegation, viewed as &#8220;heavyweight patterns&#8221; in some languages, become one-liners. And any fractional slowdown you <em>do</em> experience from an extra test run here and there will be more than made up for by the ease of changing your loosely-coupled code as requirements change. With discipline and practice, it is possible to be both <a href="http://avdi.org/devblog/2011/01/07/fast-and-good/">fast and good</a>.</p>
<h3>Conclusion</h3>
<p>To summarize:</p>
<ul>
<li><code>#try</code> is more often than not indicative of structural coupling. Structural coupling, in turn, violates the DRY principle.</li>
<li>Structural coupling, left unchecked, can substantially slow the evolution of a project.</li>
<li>The Law of Demeter, which sets limits on the number of types a single method can interact with, is a heuristic for identifying code that (among other positive properties) has low structural coupling.</li>
<li>When refactor our code to comply with the Law of Demeter, it tends to reduce structural coupling both in application code and in tests. As a side effect, it tends to eliminate the need for <code>#try</code> calls and similar constructs.</li>
<li>Contrary to popular belief, Demeter does not limit the number of of dots in a method call chain. It also doesn&#8217;t limit the number of classes a class can interact with.</li>
<li>The best way to incorporate Demeter into your work is to make it a habit, rather than a cleanup chore.</li>
</ul>
<p>Do you look for Demeter violations in your code? Do you think there are still some instances where a <code>#try</code> makes sense? Do you have more questions about the Law of Demeter or structural coupling? As always, I welcome feedback in the comments!</p>
<p><i>P.S. It&#8217;s my birthday! To celebrate, for 24 hours I&#8217;m offering <strong>50%</strong> off on my book, <a href="http://exceptionalruby.com?utm_campaign=catchthrow"><cite>Exceptional Ruby</cite></a>. Use code <code>HAPPY0X1F</code> to get the discount.</i></p>
]]></content:encoded>
			<wfw:commentRss>http://devblog.avdi.org/2011/07/05/demeter-its-not-just-a-good-idea-its-the-law/feed/</wfw:commentRss>
		<slash:comments>72</slash:comments>
		</item>
	</channel>
</rss>
