<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><!--Generated by Squarespace Site Server v5.5.4 (http://www.squarespace.com/) on Sun, 19 Jul 2009 21:10:32 GMT--><feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0"><title>Blog of Paul Ingles</title><subtitle>Articles</subtitle><id>http://oobaloo.co.uk/articles/</id><link rel="alternate" type="application/xhtml+xml" href="http://oobaloo.co.uk/articles/" /><updated>2008-08-26T23:58:39Z</updated><generator uri="http://www.squarespace.com/" version="Squarespace Site Server v5.5.4 (http://www.squarespace.com/)">Squarespace</generator><link rel="license" type="text/html" href="http://creativecommons.org/licenses/by-nc-sa/2.0/" /><link rel="self" href="http://feeds.feedburner.com/oobaloo" type="application/atom+xml" /><entry><title>Ruby Influenced C#</title><category term="c#" /><id>http://oobaloo.co.uk/articles/2008/5/7/ruby-influenced-c.html</id><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/oobaloo/~3/7hXCK3_JaxM/ruby-influenced-c.html" /><author><name>Paul</name></author><published>2008-05-07T20:07:00Z</published><updated>2008-05-07T20:07:00Z</updated><content type="html" xml:lang="en-GB">&lt;p&gt;Before joining my current project I spent about 4 months working with Ruby every day, the first time I’d done so for a few years. It was a glorious time: uncluttered syntax, closures, internal iterators, and with open classes, the ability to extend the ‘core’ at will.&lt;/p&gt;&lt;p&gt;Today I’m working with C# and .NET, and I’ve noticed that those 4 months with Ruby have changed the way I’ve been writing code. Most noticeably, I’m using anonymous delegates a &lt;em&gt;lot&lt;/em&gt; more. But that’s not all.&lt;/p&gt;&lt;p&gt;I’ve found myself aching to use the &lt;a href="http://msdn2.microsoft.com/en-us/library/bwabdf9z.aspx"&gt;&lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt;’s &lt;code&gt;ForEach&lt;/code&gt; method&lt;/a&gt;; I’m now wired to use Ruby’s internal iterators where instead of &lt;/p&gt;

&lt;pre name="code" class="csharp"&gt;
List&lt;Person&gt; people = FindAllPeople();
foreach (Person person in people) {
   ...
}
&lt;/pre&gt;

&lt;p&gt;I can instead do&lt;/p&gt;

&lt;pre name="code" class="csharp"&gt;
List&amp;lt;Person&amp;gt; people = FindAllPeople();
people.ForEach(delegate(Person person) {
  Console.WriteLine(person.Name);
});
&lt;/pre&gt;

&lt;p&gt;But, frequently I’m put off by the surrounding guff that’s needed to express the same and have almost always gone back to the more traditional external iterator-based approach. It’s simply too high-a-price to pay. &lt;/p&gt;&lt;p&gt;One of the largest smells I’ve noticed recently (to my mind) appears driven out of not having open classes and external iterators. If they were there, I’m sure people would use them. The result: all across the codebase, whenever you need to convert from type to another you’ll see&lt;/p&gt;

&lt;pre name="code" class="csharp"&gt;
List&amp;lt;Person&amp;gt; people = FindAllPeople();
List&amp;lt;String&amp;gt; firstNames = new List&amp;lt;String&amp;gt;();

foreach (Person person in people) {
  firstNames.Add(person.Name);
}
&lt;/pre&gt;

&lt;p&gt;This smells to me. But it really, really smells from having used Ruby where I would previously have written something as succinctly as this:&lt;/p&gt;

&lt;pre name="code" class="ruby"&gt;
find_all_people.collect {|person| person.name}
&lt;/pre&gt;

&lt;p&gt;(I’m sure other languages could do equally good things- but I’m familiar with Ruby, before the Pythonists pounce :p)&lt;/p&gt;&lt;p&gt;Well, turns out that you can get nearly there with C# 2.0 and .NET 2.0 with the almost certainly underused &lt;a href="http://msdn.microsoft.com/en-us/library/73fe8cwf.aspx"&gt;&lt;code&gt;ConvertAll&lt;/code&gt; method&lt;/a&gt; (also part of &lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt;).&lt;/p&gt;

&lt;pre name="code" class="csharp"&gt;
List&amp;lt;Person&amp;gt; people = FindAllPeople();
List&amp;lt;String&amp;gt; names = people.ConvertAll(delegate(Person person) {
  return person.Name;
});
&lt;/pre&gt;

&lt;p&gt;There’s still a fair bit of &lt;a href="http://memeagora.blogspot.com/2007/09/ruby-matters-meta-programming-synthesis.html"&gt;accidental complexity&lt;/a&gt; remaining- lot’s of &lt;code&gt;delegate&lt;/code&gt; and type declarations. &lt;/p&gt;&lt;p&gt;C# 3.0 introduced lambda expressions and we can use that to bubble our soup down to a nice intentional broth even more. We can get rid of the delegate bumpf and let the compiler &lt;em&gt;infer&lt;/em&gt; the type (we are still statically typed after all)&lt;/p&gt;

&lt;pre name="code" class="csharp"&gt;
List&amp;lt;Person&amp;gt; people = FindAllPeople();&lt;br/&gt;List&amp;lt;String&amp;gt; names = people.ConvertAll(person =&amp;gt; person.Name);
&lt;/pre&gt;

&lt;p&gt;Next step, we can also infer the types for our local variables:&lt;/p&gt;

&lt;pre name="code" class="csharp"&gt;
var people = FindAllPeople();
var names = people.ConvertAll(person =&amp;gt; person.Name);
&lt;/pre&gt;

&lt;p&gt;Pretty nice. Most of the code is focused on the task at hand, and on expressing the necessary complexity (what it means to convert people to names). Guess &lt;a href="http://www.pragmaticprogrammer.com/"&gt;learning a new language each year&lt;/a&gt; has it’s benefits.&lt;/p&gt;&lt;p&gt;I’ve got another bit of Ruby influenced C# refactoring to cover (a somewhat declarative way of removing switch statements), hopefully I’ll get that posted tomorrow!&lt;/p&gt;
&lt;img src="http://feeds.feedburner.com/~r/oobaloo/~4/7hXCK3_JaxM" height="1" width="1"/&gt;</content><feedburner:origLink>http://oobaloo.co.uk/articles/2008/5/7/ruby-influenced-c.html</feedburner:origLink></entry><entry><title>Prioritising Work</title><id>http://oobaloo.co.uk/articles/2008/5/1/prioritising-work.html</id><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/oobaloo/~3/wwOWUstJg7w/prioritising-work.html" /><author><name>Paul</name></author><published>2008-05-01T19:37:00Z</published><updated>2008-05-01T19:37:00Z</updated><content type="html" xml:lang="en-GB">&lt;p&gt;I was involved in the inception work (and the resulting delivery) for a project late summer last year. We estimated the total work to be nearly 500 units- too much to complete in the time we had. So, working with the client we cut it down to a reasonable scope (this client rocked at that!) of around a third.&lt;/p&gt;&lt;p&gt;What was really cool, however, was that a few months in after that initial scope had been delivered, we looked ahead for what we’d do next. According to our original inception, there was still more than double left to go, but, instead what we planned to do next was radically different. What we’d believed to be important 3 months ago, no longer was. The result was we delivered about 30% more, and about 50% overall was not part of that initial (500 unit) scope.&lt;/p&gt;&lt;p&gt;The real key was that our client had a very definite focus on work that was important (that is, work that delivers the most value) and avoided getting drawn into unimportant but urgent work, or left valuable work to the point it was always urgent. If you’re always working on urgent things you’re working at breaking point and miss out on the opportunity on higher value items that are less urgent.&lt;/p&gt;&lt;p&gt;Here’s a diagram to show the two&lt;/p&gt;&lt;p&gt;&lt;img src="http://oobaloo.co.uk/storage/assets/Urgent_and_Important_1.png" alt="Alt text"/&gt;&lt;/p&gt;&lt;p&gt;(&lt;a href="http://en.wikipedia.org/wiki/First_Things_First_%28book%29"&gt;More can be read about Covey’s grid on Wikipedia&lt;/a&gt;)&lt;/p&gt;&lt;p&gt;The right-most two quadrants (coloured blue and purple) are the key. Both represent sections that involve working on things that are valuable, i.e. those that are important to do. In contrast, 1 and 2 (the uncoloured boxes) are relatively unimportant and &lt;em&gt;should&lt;/em&gt; demand less attention. &lt;/p&gt;&lt;p&gt;The rub (of course) is that urgent things tend to be shouty and demand attention. I would also say it’s often easier to measure how urgent something is rather than how important it is; as a result, urgency is an easier (and thus more likely) benchmark for prioritising tasks - despite ignoring whether the work is worth doing at all.&lt;/p&gt;&lt;p&gt;Some of the best people I’ve worked with (including our sponsor at our client last year) have a remarkable ability to cut through the context and spot what’s really important &lt;em&gt;now&lt;/em&gt;; as opposed to just reacting to what’s demanding our attention now.&lt;/p&gt;
&lt;img src="http://feeds.feedburner.com/~r/oobaloo/~4/wwOWUstJg7w" height="1" width="1"/&gt;</content><feedburner:origLink>http://oobaloo.co.uk/articles/2008/5/1/prioritising-work.html</feedburner:origLink></entry><entry><title>Poor Man's C# Singleton Checker</title><category term="c#" /><category term="cygwin" /><category term="singleton" /><id>http://oobaloo.co.uk/articles/2008/4/7/poor-mans-c-singleton-checker.html</id><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/oobaloo/~3/lG6hLpGTj10/poor-mans-c-singleton-checker.html" /><author><name>Paul</name></author><published>2008-04-07T19:05:00Z</published><updated>2008-04-07T19:05:00Z</updated><content type="html" xml:lang="en-GB">&lt;p&gt;&lt;a href="http://paulhammant.com"&gt;Paul Hammant&lt;/a&gt; wrote a nice &lt;a href="http://www.infoq.com/articles/drinking-your-guice-too-quickly"&gt;article about how to refactor the &amp;#8220;nest-of-singletons design&amp;#8221; towards  using dependency injection using Google&amp;#8217;s Guice IoC Container&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Whilst waiting for one of my many builds to finish today, I figured I&amp;#8217;d satisfy a curiosity - roughly how many singletons are there defined within this codebase. I fired up &lt;a href="http://www.cygwin.com/"&gt;Cygwin&lt;/a&gt; and used the following&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;    &lt;p&gt;find . -type f -name &amp;#8220;*.cs&amp;#8221; | xargs cat | grep &amp;#8220;public static [A-Za-z]&amp;#92;{1,100&amp;#92;} Instance&amp;#8221; | wc -l&lt;/p&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;Result:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;    &lt;p&gt;180&lt;/p&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;Yikes!&lt;/p&gt;&lt;p&gt;For Java, you can always use the &lt;a href="http://code.google.com/p/google-singleton-detector/"&gt;Google Singleton Checker&lt;/a&gt; which also has some &lt;a href="http://code.google.com/p/google-singleton-detector/wiki/WhySingletonsAreControversial"&gt;nice stuff about why they&amp;#8217;re controversial&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;(Update) Paul Hammant pointed out that his article wasn&amp;#8217;t about refactoring out singletons, rather, breaking away from using the service locator to dependency injection. Apologies for muddling it up a little :)&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/oobaloo/~4/lG6hLpGTj10" height="1" width="1"/&gt;</content><feedburner:origLink>http://oobaloo.co.uk/articles/2008/4/7/poor-mans-c-singleton-checker.html</feedburner:origLink></entry><entry><title>Declarative Programming with Ruby</title><category term="declarative design" /><category term="metaprogramming" /><category term="ruby" /><id>http://oobaloo.co.uk/articles/2008/2/11/declarative-programming-with-ruby.html</id><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/oobaloo/~3/6WX0k-GNFt8/declarative-programming-with-ruby.html" /><author><name>Paul</name></author><published>2008-02-11T10:50:00Z</published><updated>2008-02-11T10:50:00Z</updated><content type="html" xml:lang="en-GB">&lt;p&gt;During the most recent ThoughtWorks away-day (a chance for the office to get together, catch-up, drink etc.), George and I presented on a number of Ruby and Rails lessons we learned from our (now previous) project. One of the most interesting sections (to us anyway) was on declarative programming, specifically, refactoring to a declarative design.&lt;/p&gt;&lt;p&gt;I guess much like DSLs, its easier to feel when you&amp;#8217;re achieving something declarative as opposed to necessarily defining what makes it. But, I&amp;#8217;ll try my clumsy best to define something.&lt;/p&gt;&lt;p&gt;Almost every language I&amp;#8217;ve turned my hand to (save for Erlang) are imperative languages - where programs are written as sequences of operations, with changes of state. You determine the what and the how of the system - what to do and how to do it.&lt;/p&gt;&lt;p&gt;Declarative programming is an alternative paradigm, whereby code is expressed as &lt;em&gt;what&amp;#8217;s&lt;/em&gt;. How the system executes is someone else&amp;#8217;s responsibility.&lt;/p&gt;&lt;p&gt;So, for the purposes of this discussion let&amp;#8217;s consider that application code can be split into two groups&lt;/p&gt;&lt;p&gt;&lt;ol&gt;&lt;br/&gt;&lt;li&gt;Logic- the rules, the guts of things- that &lt;em&gt;what&amp;#8217;s&lt;/em&gt;.&lt;/li&gt;&lt;br/&gt;&lt;li&gt;Control- statements about execution flow.&lt;/li&gt;&lt;br/&gt;&lt;/ol&gt;&lt;/p&gt;&lt;p&gt;Interestingly, one of the principles listed in Kent Beck&amp;#8217;s most recent book (Implementation Patterns) includes &amp;#8220;Declarative Expression&amp;#8221; - that you should be able to read what your code is doing, without having to understand the wider execution context.&lt;/p&gt;&lt;p&gt;Declarative languages are all around us, with most developers I&amp;#8217;m guessing using them almost daily.&lt;/p&gt;&lt;p&gt;Think of SQL, when you write a statement such like &lt;code&gt;SELECT [Name], [Age] FROM [Person] WHERE [Age] &amp;gt; 15&lt;/code&gt; you&amp;#8217;re making a statement about &lt;em&gt;what&lt;/em&gt; you&amp;#8217;d like, not how you get there- that&amp;#8217;s up for the database engine to figure out. And a good thing to! Have you ever taken a look at an execution plan for modestly complex queries?&lt;/p&gt;&lt;p&gt;Closter to home - think of .NET and Java Annotations- where you can decorate constructs with additional behaviours. They look and feel like core extensions to the language, but are programmable and can be used to adapt the runtime behaviour of the system. &lt;/p&gt;&lt;p&gt;Before working for ThoughtWorks, I worked on a system where we used attributes to allow us to add validations to properties, allowing us to re-use code and extend easily.&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="java"&gt;[LengthMustBeAtLeast(6)]&lt;br/&gt;public property string FirstName&lt;br/&gt;{&lt;br/&gt;  get { ... }&lt;br/&gt;  set { ... }&lt;br/&gt;}&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Everything was nicely decoupled, read well, and reduced the amount of clutter in our code. More importantly, our validation code was not spread throughout every setter of every property. We could isolate responsibilities making code easier to digest and understand, and test!&lt;/p&gt;&lt;p&gt;Onto Ruby. A substantial part of our project involved reading lots of CSV files from different sources to update our deal information. The answer was a kind of &lt;a href="http://delivery.acm.org/10.1145/1300000/1297966/p976-peng.pdf?key1=1297966&amp;amp;key2=8027567911&amp;amp;coll=GUIDE&amp;amp;dl=GUIDE&amp;amp;CFID=15151515&amp;amp;CFTOKEN=6184618"&gt;anticorruption layer&lt;/a&gt; (borrowing heavily from domain-driven design) for each different feed.&lt;/p&gt;&lt;p&gt;Quickly, we ended up with a few concrete classes and a base class that co-ordinated effort. Dependencies were shared both ways, imagine a number of template methods that are called in sequence to accomplish their work. Over time it grew complex, and with Ruby it&amp;#8217;s a little tougher (than with languages like Java or .NET) to navigate and browse around the code without strong IDE support.&lt;/p&gt;&lt;p&gt;It was starting to get a little too complex and we felt we needed to change things, so we did (bolstered somewhat by having &lt;a href="http://blog.jayfields.com"&gt;Jay&lt;/a&gt; with us).&lt;/p&gt;&lt;p&gt;Onto the code.&lt;/p&gt;&lt;p&gt;So imagine we have a class representing a &lt;code&gt;Feed&lt;/code&gt; of information (read from a CSV file), and we want to be able to ask that &lt;code&gt;Feed&lt;/code&gt; to provide us with a number of &lt;code&gt;Deals&lt;/code&gt;. Internally, it will iterate over the items in the &lt;code&gt;Feed&lt;/code&gt;, creating a &lt;code&gt;Deal&lt;/code&gt; for each one (if possible).&lt;/p&gt;&lt;p&gt;Our first solution looked a little like this, firstly in the &amp;#8216;abstract&amp;#8217; base class:&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="ruby"&gt;def create_deal&lt;br/&gt;  Deal.create(:network_name =&amp;gt; network_name)&lt;br/&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;and in the feed&amp;#8217;s concrete implementation:&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="ruby"&gt;FIELD_INDICES = {:name =&amp;gt; 1, :network_name =&amp;gt; 2}&lt;/p&gt;&lt;p&gt;def network_name&lt;br/&gt;  read_cell(FIELD_INDICES[:network_name])&lt;br/&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Our main feed class asks our implementation class for the &lt;code&gt;network_name&lt;/code&gt; - a template method. Not bad, now build that up to tens of attributes, a bit longer. Since we&amp;#8217;ve defined column indices in a constant, we also now have to navigate up and down lots to determine where we&amp;#8217;re reading from. Add in a few other tables with look-ups for other bits that we need to do the mapping and it can get a little complex pretty quick.&lt;/p&gt;&lt;p&gt;Our code is not only made up of the stuff determining what it is to translate between a CSV representation of our Deals to an object model one, but also all of the code necessary to find out which CSV column we&amp;#8217;re in, how we map that column etc. They were essentially just reading values from cells, no translation needed. Most of the code we had was infrastructural, and the logic (the &lt;em&gt;what&lt;/em&gt; of our application) was hidden amongst the noise.&lt;/p&gt;&lt;p&gt;This complexity, combined with the split of flow between abstract and concrete classes, made it difficult to follow and understand. Our goal was to try and reduce each concrete implementation to a single page on our screens.&lt;/p&gt;&lt;p&gt;These little &amp;#8216;mapping&amp;#8217; translation methods were our first target - reduce the amount of code for each of these to one line that described the mapping, rather than how we get it all.&lt;/p&gt;&lt;p&gt;Firstly, we introduced a convention - every attribute of a &lt;code&gt;Deal&lt;/code&gt; could be retrieved by calling a &lt;code&gt;deal_attribute_my_attribute&lt;/code&gt; style method. So, we renamed all our methods, ran the tests, and then started to make steps towards having each &lt;code&gt;deal_attribute_blah&lt;/code&gt; method defined dynamically.&lt;/p&gt;&lt;p&gt;We went from:&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="ruby"&gt;def network&lt;br/&gt;  ...&lt;br/&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;to&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="ruby"&gt;def deal_attribute_network&lt;br/&gt;  ...&lt;br/&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;to &amp;#8230; nothing.&lt;/p&gt;&lt;p&gt;Well, not quite. Instead, what we wanted was to have a method constructed by adding a class method to a module that we could mix-in. Then, we could just define the mapping and Ruby would wire up the rest. We settled on the following syntax&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="ruby"&gt;deal_attribute :name =&amp;gt; 'NAME'&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Neat. A little class&lt;em&gt;eval and instance&lt;/em&gt;eval magic later we were able to push our infrastructural code out of our concrete feed class and into the co-ordinator.&lt;/p&gt;&lt;p&gt;Our code is now more declarative. We&amp;#8217;re stating what we need to do our work, rather than worrying about how we get at it. Not only that, for the common case (where we may be just moving values from one place to another) there&amp;#8217;s no need to do anything more than describe that relationship. Declarative programming makes it much easier to express important relationships. It&amp;#8217;s now much easier to see the relationship between the &lt;code&gt;name&lt;/code&gt; attribute of a &lt;code&gt;Deal&lt;/code&gt; and the &lt;code&gt;NAME&lt;/code&gt; column for this CSV feed.&lt;/p&gt;&lt;p&gt;Notice also how we&amp;#8217;re pushing our dependencies up to our caller- the coupling is now one-way. We state what we need from our caller (the main deal feed class) - our caller is able to then pass the information on. We&amp;#8217;re just answering questions, rather than answering questions and asking questions (of our caller).&lt;/p&gt;&lt;p&gt;The syntax also lends itself to explaining a dependency, that an attribute of our deal is read from &amp;#8216;NAME&amp;#8217; (for example).&lt;/p&gt;&lt;p&gt;That&amp;#8217;s great, next step was to tidy up some of the slightly more complex examples where we do some additional translation. For example, where we take the name of something and we need to pull back an object from the database instead. Let&amp;#8217;s say we keep track of the &lt;code&gt;Phone&lt;/code&gt; that a &lt;code&gt;Deal&lt;/code&gt; is for. &lt;/p&gt;&lt;p&gt;So, from&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;def deal_attribute_phone&lt;br/&gt;  Phone.find(deal_attribute_brand, deal_attribute_model)&lt;br/&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;to&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="ruby"&gt;deal_attribute(:phone =&amp;gt; ['MAKE', 'MODELNAME']) do |brand, model|&lt;br/&gt;  Phone.find(brand, model)&lt;br/&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;We&amp;#8217;ve extended the syntax to reveal that this translation needs values from both the &amp;#8216;MAKE&amp;#8217; and &amp;#8216;MODELNAME&amp;#8217; columns. From our perspective, we&amp;#8217;re pushing responsibility up and keeping our code focused on what we need to map this attribute.&lt;/p&gt;&lt;p&gt;This is a little more complex to achieve since we&amp;#8217;re also passing arguments across (and our &lt;code&gt;deal_attribute&lt;/code&gt; translator methods also sometimes need to access instance variables) so we need to use &lt;a href="http://www.oobaloo.co.uk/articles/2007/11/4/meta-programming-with-instance_exec"&gt;&lt;code&gt;instance_exec&lt;/code&gt;&lt;/a&gt; instead of the standard &lt;code&gt;instance_eval&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;The end result was feed classes that looked as follows&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="ruby"&gt;class MySpecialFeed&lt;br/&gt;  deal_attribute :name =&amp;gt; 'NAME'&lt;br/&gt;  deal_attribute(:description =&amp;gt; 'DESC') {|desc| cleanse_description(desc) }&lt;br/&gt;  deal_attribute(:phone =&amp;gt; ['MAKE', 'MODELNAME']) do |brand, model|&lt;br/&gt;    Phone.find(brand, model)&lt;br/&gt;  end&lt;br/&gt;  ...&lt;br/&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;In total, it took us probably just over a day to refactor the code for all of our classes. Most of which we managed to get down to some 40 or 50 lines total. We didn&amp;#8217;t refactor all the code, so there&amp;#8217;s still potential for exploiting it further but it was definitely a very exciting thing to see happen. &lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/oobaloo/~4/6WX0k-GNFt8" height="1" width="1"/&gt;</content><feedburner:origLink>http://oobaloo.co.uk/articles/2008/2/11/declarative-programming-with-ruby.html</feedburner:origLink></entry><entry><title>Copying Classes</title><category term="metaprogramming" /><category term="ruby" /><id>http://oobaloo.co.uk/articles/2007/11/15/copying-classes.html</id><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/oobaloo/~3/dj04d0Wb2zI/copying-classes.html" /><author><name>Paul</name></author><published>2007-11-15T20:02:00Z</published><updated>2007-11-15T20:02:00Z</updated><content type="html" xml:lang="en-GB">&lt;p&gt;From across the desk, &lt;a href="http://nutrun.com/"&gt;George&lt;/a&gt; asks &amp;#8220;can you copy classes in Ruby?&amp;#8221;. We talk about it quickly and reason that since everything&amp;#8217;s an Object (even classes), you probably can. Since the constant isn&amp;#8217;t changed or duplicated (you&amp;#8217;re essentially assigning a new one) then it ought to be possible.&lt;/p&gt;&lt;p&gt;Turns out it is!&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="ruby"&gt;class First&lt;br/&gt;  def initialize&lt;br/&gt;    @value = 99&lt;br/&gt;  end&lt;/p&gt;&lt;p&gt;  def say_value&lt;br/&gt;    @value&lt;br/&gt;  end&lt;br/&gt;end&lt;br/&gt;First.new.say_value # =&amp;gt; 99&lt;/p&gt;&lt;p&gt;Second = First.clone&lt;br/&gt;Second.class_eval do&lt;br/&gt;  define_method :say_value do&lt;br/&gt;    @value + 100&lt;br/&gt;  end&lt;br/&gt;end&lt;br/&gt;Second.new.say_value # =&amp;gt; 199&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Neat.&lt;/p&gt;&lt;p&gt;I&amp;#8217;m not sure quite why you would want to &lt;em&gt;clone&lt;/em&gt; a class to take advantage of re-use - rather than extract to a module (and share the implementation that way) or, if there&amp;#8217;s a strong relationship that doesn&amp;#8217;t violate the &lt;a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle"&gt;LSP&lt;/a&gt; etc. then look for some kind of inheritance-based design.&lt;/p&gt;&lt;p&gt;But, I guess you could work some kind of cool ultra-dynamic super-meta system from it. Perhaps someone with way more of a Ruby-thinking brain than me could offer some thoughts?&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/oobaloo/~4/dj04d0Wb2zI" height="1" width="1"/&gt;</content><feedburner:origLink>http://oobaloo.co.uk/articles/2007/11/15/copying-classes.html</feedburner:origLink></entry><entry><title>Watch out for the Monkey Patch</title><category term="monkeypatch" /><category term="rails" /><category term="ruby" /><id>http://oobaloo.co.uk/articles/2007/11/8/watch-out-for-the-monkey-patch.html</id><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/oobaloo/~3/Rm5i_9fchyE/watch-out-for-the-monkey-patch.html" /><author><name>Paul</name></author><published>2007-11-08T09:35:00Z</published><updated>2007-11-08T09:35:00Z</updated><content type="html" xml:lang="en-GB">&lt;p&gt;The project I&amp;#8217;m currently working on uses both the &lt;a href="http://synthesis.sbecker.net/pages/asset_packager"&gt;Asset Packager&lt;/a&gt; and &lt;a href="http://trac.poocs.net/plugins/wiki"&gt;Distributed Assets&lt;/a&gt; to ensure we have only a few external assets, and that we can load assets across more than one host - all so that the pages for our site load nice and quick.&lt;/p&gt;&lt;p&gt;Unfortunately, wiring in the Asset Packager plugin caused the Distributed Assets plugin to break, and I spent an hour or two tracking it down yesterday. The cause? Asset Packager redefines the &lt;code&gt;compute_public_path&lt;/code&gt; method.&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="ruby"&gt;# rewrite compute_public_path to allow us to not include the query string timestamp&lt;br/&gt;    # used by ActionView::Helpers::AssetTagHelper&lt;br/&gt;    def compute_public_path(source, dir, ext=nil, add_asset_id=true)&lt;br/&gt;      source = source.dup&lt;br/&gt;      source &amp;lt;&amp;lt; &amp;quot;.#{ext}&amp;quot; if File.extname(source).blank? &amp;amp;&amp;amp; ext&lt;br/&gt;      unless source =~ %r{^[-a-z]+://}&lt;br/&gt;        source = &amp;quot;/#{dir}/#{source}&amp;quot; unless source[0] == ?/&lt;br/&gt;        asset_id = rails_asset_id(source)&lt;br/&gt;        source &amp;lt;&amp;lt; '?' + asset_id if defined?(RAILS_ROOT) and add_asset_id and not asset_id.blank?&lt;br/&gt;        source = &amp;quot;#{ActionController::Base.asset_host}#{@controller.request.relative_url_root}#{source}&amp;quot;&lt;br/&gt;      end&lt;br/&gt;      source&lt;br/&gt;    end&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Distributed Assets works by chaining &lt;code&gt;compute_public_path&lt;/code&gt; - &lt;a href="http://en.wikipedia.org/wiki/Decorator_pattern"&gt;decorating&lt;/a&gt; the calculated path, adding the asset host prefix onto the url. But, Asset Packager works by defining the method into &lt;code&gt;ActionView::Base&lt;/code&gt;. So, when &lt;code&gt;DistributedAssets::AssetTagHelper&lt;/code&gt; is included with &lt;code&gt;ActionView::Helpers::AssetTagHelper&lt;/code&gt;, it chains a (now) hidden method.&lt;/p&gt;&lt;p&gt;But, the only places that use the new &lt;code&gt;compute_public_path&lt;/code&gt; code inside the Asset Packager Helper (which just avoids using the query string timestamp) is within Asset Packager itself.&lt;/p&gt;&lt;p&gt;So, I tweaked the implementation of &lt;code&gt;AssetPackageHelper&lt;/code&gt; to&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="ruby"&gt;def compute_public_path_for_packager(source, dir, ext, add_asset_id=true)&lt;br/&gt;  path = compute_public_path(source, dir, ext)&lt;br/&gt;  return path if add_asset_id&lt;br/&gt;  path.gsub(/\?\d+$/, '')&lt;br/&gt;end&lt;/p&gt;&lt;p&gt;def javascript_path(source)&lt;br/&gt;  compute_public_path_for_packager(source, 'javascripts', 'js', false)       &lt;br/&gt;end&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Beware the monkey patch.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/oobaloo/~4/Rm5i_9fchyE" height="1" width="1"/&gt;</content><feedburner:origLink>http://oobaloo.co.uk/articles/2007/11/8/watch-out-for-the-monkey-patch.html</feedburner:origLink></entry><entry><title>Meta-programming with instance_exec</title><category term="metaprogramming" /><category term="ruby" /><category term="rubyfacets" /><id>http://oobaloo.co.uk/articles/2007/11/4/meta-programming-with-instance_exec.html</id><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/oobaloo/~3/Ex6YaBlG980/meta-programming-with-instance_exec.html" /><author><name>Paul</name></author><published>2007-11-04T11:57:00Z</published><updated>2007-11-04T11:57:00Z</updated><content type="html" xml:lang="en-GB">&lt;p&gt;&lt;a href="http://www.rubyonrails.org"&gt;Rails&lt;/a&gt; makes heavy use of a declarative style around it&amp;#8217;s codebase- for example the &lt;code&gt;has_one&lt;/code&gt; and &lt;code&gt;belongs_to&lt;/code&gt; declarations inside &lt;code&gt;ActiveRecord&lt;/code&gt; (amongst others). These are just class methods defined on modules, letting Rails wire up relationships, but they read like fully-fledged statements within a mini-language:&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="ruby"&gt;class Student &amp;lt; ActiveRecord::Base&lt;br/&gt;  has_many :tutorials&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;We can take advantage of the same in our code- letting us write in a declarative-style (hopefully revealing stronger intent) and reduce the amount of code we write (by using declarations to meta-program for us). I posted a little while ago that we&amp;#8217;d used such &lt;a href="http://oobaloo.co.uk/articles/2007/9/10/immutable-activerecord-attributes"&gt;an approach for marking attributes as immutable&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Anyway, back to the title of the post- &lt;a href="http://facets.rubyforge.org/rdoc/Core/classes/Kernel.html#M000365"&gt;&lt;code&gt;#instance_exec&lt;/code&gt;&lt;/a&gt;, it&amp;#8217;s a method defined in &lt;a href="http://facets.rubyforge.org"&gt;Ruby Facets&lt;/a&gt;. Like it&amp;#8217;s documentation says, it&amp;#8217;s equivalent to &lt;code&gt;instance_eval&lt;/code&gt; but also lets you pass parameters- roll on the meta magic.&lt;/p&gt;&lt;p&gt;Let&amp;#8217;s say we&amp;#8217;re writing a system to calculate the monthly salary payment for an employee. We want to be able to say &lt;em&gt;what&lt;/em&gt; the payment is rather than &lt;em&gt;how&lt;/em&gt; it&amp;#8217;s calculated. &lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="ruby"&gt;class FullTimeEmployee&lt;br/&gt;  include Employee&lt;/p&gt;&lt;p&gt;  bill_at {|hours| 50.pounds_sterling * hours}&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;In the snippet above, we&amp;#8217;re making a declaration - defining the relationship between an hourly rate and the number of hours the employee works. We can implement &lt;code&gt;bill_at&lt;/code&gt; in &lt;code&gt;Employee&lt;/code&gt; as follows:&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="ruby"&gt;module Employee&lt;br/&gt;  module ClassMethods&lt;br/&gt;    def bill_at &amp;amp;block&lt;br/&gt;      define_method(:calculate_bill) do |hours|&lt;br/&gt;        instance_exec hours, &amp;amp;block&lt;br/&gt;      end&lt;br/&gt;  ...&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Our assertion could be:&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code class="ruby"&gt;assert_equal 500.pounds_sterling, employee.calculate_bill(5.hours)&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/oobaloo/~4/Ex6YaBlG980" height="1" width="1"/&gt;</content><feedburner:origLink>http://oobaloo.co.uk/articles/2007/11/4/meta-programming-with-instance_exec.html</feedburner:origLink></entry><entry><title>DTrace in Leopard with Ruby probes</title><category term="dtrace" /><category term="osx" /><category term="rails" /><category term="ruby" /><id>http://oobaloo.co.uk/articles/2007/10/29/dtrace-in-leopard-with-ruby-probes.html</id><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/oobaloo/~3/hopbDM9a_Z8/dtrace-in-leopard-with-ruby-probes.html" /><author><name>Paul</name></author><published>2007-10-29T21:20:00Z</published><updated>2007-10-29T21:20:00Z</updated><content type="html" xml:lang="en-GB">&lt;p&gt;I&amp;#8217;d read a while back that Apple were going to include &lt;a href="http://www.sun.com/software/solaris/howtoguides/dtracehowto.jsp"&gt;Sun&amp;#8217;s DTrace tool&lt;/a&gt; in the now newly released Leopard - underpinning &lt;a href="http://www.apple.com/macosx/developertools/instruments.html"&gt;Instruments&lt;/a&gt; (formerly known as Xray).&lt;/p&gt;&lt;p&gt;What I &lt;em&gt;hadn&amp;#8217;t&lt;/em&gt; noticed was that the build of Ruby 1.8.6 included in Leopard (patchlevel 36 with some extras) also includes &lt;a href="https://dtrace.joyent.com/projects/ruby-dtrace/wiki/Ruby+DTrace"&gt;Ruby probes&lt;/a&gt; from the lovely folks at &lt;a href="http://www.joyent.com"&gt;Joyent&lt;/a&gt;. Apple have ported everything. So, out of the box, Ruby works with DTrace! Sweet!&lt;/p&gt;&lt;p&gt;From Sun&amp;#8217;s page:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;    &lt;p&gt;DTrace is a comprehensive dynamic tracing facility that is built into Solaris and can be used by administrators and developers to examine the behavior of both user programs and of the operating system itself. With DTrace you can explore your system to understand how it works, track down performance problems across many layers of software, or locate the cause of aberrant behavior.&lt;/p&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;Joyent have got some &lt;a href="http://svn.joyent.com/opensource/dtrace/ruby/examples/"&gt;sample scripts&lt;/a&gt; in their Subversion repository, and, what looks like some nice &lt;a href="http://svn.joyent.com/opensource/dtrace/ruby/examples/rails/"&gt;extensions for Rails&lt;/a&gt; (DTrace probes can be fired from within Ruby). Blimey!&lt;/p&gt;&lt;p&gt;For those (running Leopard) and want to just see something, &lt;a href="http://pingles.bingodisk.com/bingo/public/functime.d"&gt;try this out&lt;/a&gt;. It&amp;#8217;s a script that traces the number of times a method is called. Once downloaded, all you need to do is&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;$ chmod +x functime.d&lt;br/&gt;$ sudo ./functime.d -p &amp;lt;pid&amp;gt;&lt;br/&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Replacing &lt;code&gt;&amp;lt;pid&amp;gt;&lt;/code&gt; with the process id for your target Ruby process. Once you stop tracing (or your target process ends you&amp;#8217;ll see some nice text formatted output. Including something like the following (from my current project):&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;Hash                     key?                     25123         15       384174&lt;br/&gt;Module                   each_object                  1     390824       390824&lt;br/&gt;Module                   included_in_classes          1     391025       391025&lt;br/&gt;Module                   reloadable_classes_with      1     391203       391203&lt;br/&gt;Module                   reloadable_classes           1     391835       391835&lt;br/&gt;ActionController::Routin load_routes!                 1     394864       394864&lt;br/&gt;ActionController::Routin reload                       1     398364       398364&lt;br/&gt;Class                    reset_application!           1     398947       398947&lt;br/&gt;Class                    reset_after_dispatch         1     400474       400474&lt;br/&gt;ActionController::Routin connect                     39      13192       514506&lt;br/&gt;Array                    include?                  3353        166       556605&lt;br/&gt;ActionController::Routin build                       47      13116       616459&lt;br/&gt;ActionController::Routin add_route                   47      13329       626488&lt;br/&gt;Array                    each                       874        780       682423&lt;br/&gt;Object                   load                         2     376432       752864&lt;br/&gt;Module                   silence                      2     391586       783172&lt;br/&gt;Kernel                   gem_original_require        28      43460      1216884&lt;br/&gt;Array                    select                     316       4106      1297580&lt;br/&gt;Array                    collect                    351       4124      1447524&lt;br/&gt;Module                   local_constants             91      17120      1557986&lt;br/&gt;Module                   new_constants_in            25      93885      2347139&lt;br/&gt;Object                   require                     50      58495      2924783&lt;br/&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;The columns (from left to right) are: Class, Method, Count (number of times method was called) and then the average and total micro seconds. The d script was &lt;a href="http://svn.joyent.com/opensource/dtrace/ruby/examples/rb_functime.d"&gt;one of the Joyent examples&lt;/a&gt;. Arstechnica also have a &lt;a href="http://arstechnica.com/reviews/os/mac-os-x-10-5.ars/5/#dtrace"&gt;very cool example&lt;/a&gt; showing the call stack from a system call.&lt;/p&gt;&lt;p&gt;What&amp;#8217;s more amazing is this doesn&amp;#8217;t require any recompilation, special flags, running in special environments. It&amp;#8217;s available from the off!&lt;/p&gt;&lt;p&gt;If all that&amp;#8217;s whetted your appetite (and I&amp;#8217;m not sure how it couldn&amp;#8217;t), head on over to the &lt;a href="http://www.sun.com/software/solaris/howtoguides/dtracehowto.jsp"&gt;DTrace how to&lt;/a&gt; for a little more explanation of how it all works.&lt;/p&gt;&lt;p&gt;Time to get stuck in and see whether anything emerges about my current project. Very cool stuff!&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/oobaloo/~4/hopbDM9a_Z8" height="1" width="1"/&gt;</content><feedburner:origLink>http://oobaloo.co.uk/articles/2007/10/29/dtrace-in-leopard-with-ruby-probes.html</feedburner:origLink></entry><entry><title>New Repository URL for Mephisto Flickr Plugin</title><category term="mephisto,flickr" /><id>http://oobaloo.co.uk/articles/2007/10/2/new-repository-url-for-mephisto-flickr-plugin.html</id><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/oobaloo/~3/tg5Hk3gpR44/new-repository-url-for-mephisto-flickr-plugin.html" /><author><name>Paul</name></author><published>2007-10-02T20:54:00Z</published><updated>2007-10-02T20:54:00Z</updated><content type="html" xml:lang="en-GB">&lt;p&gt;I&amp;#8217;ve recently had a few people email me about problems with the Mephisto Flickr plugin I wrote, that Liquid (the templating engine used in Mephisto) had changed the interface for the initializer.&lt;/p&gt;&lt;p&gt;I thought I&amp;#8217;d fixed it a few times, and indeed I had. Just in the wrong repository! Sorry. I guess I&amp;#8217;ve still not quite managed to get the hang of aliased virtual hosts on TextDrive shared hosting.&lt;/p&gt;&lt;p&gt;So instead you should take a look at doing&lt;/p&gt;&lt;p&gt;&lt;pre&gt;&lt;code&gt;$ script/plugin install http://svn.oobaloo.co.uk/svn/mephisto_plugins/mephisto_flickr_photo_stream/trunk &amp;amp;&amp;amp; mv vendor/plugins/trunk vendor/plugins/mephisto_flickr_photo_stream&lt;br/&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Note that it&amp;#8217;s now reading from &lt;code&gt;svn.oobaloo.co.uk&lt;/code&gt;. Sorry for the confusion. I&amp;#8217;ll try and figure out how to get engross.org pointing to the right location in the meantime.&lt;/p&gt;&lt;p&gt;Thanks again to everyone who&amp;#8217;d emailed in with the fix, and sorry again.&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/oobaloo/~4/tg5Hk3gpR44" height="1" width="1"/&gt;</content><feedburner:origLink>http://oobaloo.co.uk/articles/2007/10/2/new-repository-url-for-mephisto-flickr-plugin.html</feedburner:origLink></entry><entry><title>The Fantastically Honest RDoc</title><category term="ruby" /><id>http://oobaloo.co.uk/articles/2007/9/12/the-fantastically-honest-rdoc.html</id><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/oobaloo/~3/sH_0LgxYG8k/the-fantastically-honest-rdoc.html" /><author><name>Paul</name></author><published>2007-09-12T19:59:00Z</published><updated>2007-09-12T19:59:00Z</updated><content type="html" xml:lang="en-GB">&lt;p&gt;Whilst working on a bit of code the other day we found this little nugget in the &lt;a href="http://www.ruby-doc.org/core/classes/Object.html#M000381"&gt;RDoc for &lt;code&gt;Object#instance_variable_set&lt;/code&gt;&lt;/a&gt;:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;    &lt;p&gt;Sets the instance variable names by symbol to object, thereby frustrating the efforts of the class‘s author to attempt to provide proper encapsulation.&lt;/p&gt;&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;Brilliant!&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/oobaloo/~4/sH_0LgxYG8k" height="1" width="1"/&gt;</content><feedburner:origLink>http://oobaloo.co.uk/articles/2007/9/12/the-fantastically-honest-rdoc.html</feedburner:origLink></entry></feed>
