<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
  <title>Saturn Flyer with Jim Gay</title>
  <description>Design and Development with Thoughtful Imagination</description>
  <link>http://www.saturnflyer.com/rss/</link>
  <language>en-us</language>
  <ttl>40</ttl>
  
  
    <item>
      <title>Commanding objects toward immutability</title>
      <dc:creator>Angela</dc:creator>
      <description>&lt;p&gt;Following the rules for East-oriented Code helps me organize behavior in my code but it can lead to other benefits as well. As a result of following &lt;a href=&quot;http://confreaks.tv/videos/rubyconf2014-eastward-ho-a-clear-path-through-ruby-with-oo&quot;&gt;the rules&lt;/a&gt;, I find that my code is better prepared for restrictions like that which immutable objects introduce.&lt;/p&gt;

&lt;p&gt;I recently went looking for samples of how people are using &lt;code&gt;instance_eval&lt;/code&gt; and &lt;code&gt;instance_exec&lt;/code&gt; and ended up with a great &lt;a href=&quot;http://www.saturnflyer.com/blog/jim/2015/04/22/the-difference-between-instance_eval-and-instance_exec/&quot;&gt;example from FactoryGirl&lt;/a&gt; thanks to Joshua Clayton. As I was searching, I came upon some code which happened to use &lt;code&gt;instance_eval&lt;/code&gt;. Although it was a simple use case for that method it lent itself as a much better example of commands, immutability, and East-oriented code.&lt;/p&gt;

&lt;p&gt;Here&amp;rsquo;s the details&amp;hellip;&lt;/p&gt;

&lt;p&gt;If we want to use nested blocks to create a tree structure, we might create some pseudo-code like this to illustrate our desired code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Node.new('root') do
  node('branch') do
    node('leaf')
    node('leaf2')
    node('leaf3')
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The representation of this set of objects should look something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;['root', ['branch', ['leaf', 'leaf2', 'leaf3']]]&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This shows that the created tree is a pair of a named node and an array of named children (who can also have children).&lt;/p&gt;

&lt;h2&gt;Imperative approach&lt;/h2&gt;

&lt;p&gt;A simple solution is to initialize a &lt;code&gt;Node&lt;/code&gt; and, using an imperative approach, to change its state; that is to say that we alter its collection of children.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Node
  def initialize(name, &amp;amp;block)
    @name = name
    @children = []

    instance_eval(&amp;amp;block) if block
  end

  attr_reader :children, :name

  def node(name, &amp;amp;block)
    children &amp;lt;&amp;lt; Node.new(name, &amp;amp;block)
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When each node is created, its collection of &lt;code&gt;children&lt;/code&gt; is set to an empty array. With each call to the &lt;code&gt;node&lt;/code&gt; method, a new &lt;code&gt;Node&lt;/code&gt; object is created and shoveled into the collection of children.&lt;/p&gt;

&lt;p&gt;If we refactor our sample to inline the methods and show us exactly what&amp;rsquo;s going on, it would look something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Node.new('root') do
  self.children &amp;lt;&amp;lt; Node.new('branch') do
    self.children &amp;lt;&amp;lt; Node.new('leaf')
    self.children &amp;lt;&amp;lt; Node.new('leaf2')
    self.children &amp;lt;&amp;lt; Node.new('leaf3')
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can more clearly see what&amp;rsquo;s happening inside of the &lt;code&gt;node&lt;/code&gt; method with this change to our code.&lt;/p&gt;

&lt;h2&gt;Eastward flow&lt;/h2&gt;

&lt;p&gt;As I worked with this problem I wondered: what would happen if I started following the 4 rules of East-oriented code?&lt;/p&gt;

&lt;p&gt;If our &lt;code&gt;node&lt;/code&gt; method returns &lt;code&gt;self&lt;/code&gt;, how does that affect our code?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Node
  # initialize omitted...

  def node(name, &amp;amp;block)
    children &amp;lt;&amp;lt; Node.new(name, &amp;amp;block)
    self
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Fortunately, because our code relies on an imperative approach by changing the state of the &lt;code&gt;children&lt;/code&gt;, the code still works.&lt;/p&gt;

&lt;p&gt;If we want, we can shrink the space we use by chaining commands together:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;t = Node.new(&quot;root&quot;) do
  node(&quot;branch&quot;) do
    node(&quot;subbranch&quot;) do
      node(&quot;leaf&quot;).node(&quot;leaf2&quot;).node(&quot;leaf3&quot;)
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I think that&amp;rsquo;s actually a little more difficult to read, so we can go back to the regular style:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;node(&quot;leaf&quot;)
node(&quot;leaf2&quot;)
node(&quot;leaf3&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When seeing techniques like returning &lt;code&gt;self&lt;/code&gt; to encourage an East-oriented approach, it&amp;rsquo;s easy to fixate on the chaining. But it&amp;rsquo;s commands that we want to introduce, not chaining. The chaining is incidental here.&lt;/p&gt;

&lt;p&gt;If you &lt;em&gt;do&lt;/em&gt; chain your method calls together, it at least appears more clearly that each subsequent method is operating on the return value of the last one.&lt;/p&gt;

&lt;p&gt;If we want to be clear that we&amp;rsquo;re operating on the last return value, we can maintain the readability of the multiline option by writing it like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;node(&quot;leaf&quot;).
node(&quot;leaf2&quot;).
node(&quot;leaf3&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Each line chains the next by adding the dot character. We don&amp;rsquo;t have a specific need to do this, but it&amp;rsquo;s good to know how it works.&lt;/p&gt;

&lt;p&gt;Not much has changed after introducing our East-oriented approach. We&amp;rsquo;re still updating that collection of &lt;code&gt;children&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;Introducing immutability&lt;/h2&gt;

&lt;p&gt;What will we see if we introduce immutable objects to our solution?&lt;/p&gt;

&lt;p&gt;Immutable objects might just help us make our code more predictable. An object which never changes, of course, stays the same. This allows you to better handle the behavior of the system and, without changing any objects, makes a multithreaded approach much less likely to introduce headaches.&lt;/p&gt;

&lt;p&gt;The simplest way to add immutability is to freeze objects as they are initialized:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Node
  def initialize(name, &amp;amp;block)
    @name = name.freeze
    @children = [].freeze

    instance_eval(&amp;amp;block) if block
  end

  attr_reader :children, :name

  def node(name, &amp;amp;block)
    children &amp;lt;&amp;lt; Node.new(name, &amp;amp;block).freeze
    self
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This, of course, breaks everything. Our code relies upon the fact that the &lt;code&gt;children&lt;/code&gt; array may be mutated. Instead of doing the mutation, we&amp;rsquo;ll see this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;RuntimeError: can't modify frozen Array
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now what?&lt;/p&gt;

&lt;p&gt;If we can&amp;rsquo;t alter the collection, we&amp;rsquo;re left at creating an entirely new one.&lt;/p&gt;

&lt;p&gt;One thing we could do is change the constructor to accept a collection of children when the &lt;code&gt;Node&lt;/code&gt; is initialized. Instead of altering the children, we&amp;rsquo;d use a constructor like this &lt;code&gt;Node.new(name, chlidren)&lt;/code&gt;. Here&amp;rsquo;s what that looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Node
  def initialize(name, children=[], &amp;amp;block)
    @name = name.freeze
    @children = children.freeze

    instance_eval(&amp;amp;block) if block
  end
  # ... omitted code

end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That still doesn&amp;rsquo;t allow us to change anything until we also change the way our &lt;code&gt;node&lt;/code&gt; method works (since it is responsible for handling changes to the children).&lt;/p&gt;

&lt;p&gt;If the &lt;code&gt;node&lt;/code&gt; method created a new &lt;code&gt;Node&lt;/code&gt; instead of altering the children, that would get us what we want. Let&amp;rsquo;s break it down.&lt;/p&gt;

&lt;p&gt;First, when the &lt;code&gt;node&lt;/code&gt; method is called, it needs to create the node to be added to the collection of children:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def node(name, &amp;amp;block)
  new_child = Node.new(name, &amp;amp;block)
  # ... ?
  self
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Since we&amp;rsquo;re trying to avoid mutating the state of this object, we don&amp;rsquo;t want to just shove the new node into the collection of children (and we can&amp;rsquo;t because we used &lt;code&gt;freeze&lt;/code&gt; on it).&lt;/p&gt;

&lt;p&gt;So let&amp;rsquo;s create an entirely new node, with an entirely new collection of children. In order to do that, we need to ensure that for every existing child object, we creat a corresponding new node.&lt;/p&gt;

&lt;p&gt;For each command to the object with &lt;code&gt;node&lt;/code&gt;, we&amp;rsquo;ll get the representation of what the children should be. So let&amp;rsquo;s build a method to do that:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def next_children
  children.map{|child| Node.new(child.name, child.next_children) }.freeze
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When we changed our initializer, that allowed us to set the list of children. Our new &lt;code&gt;next_children&lt;/code&gt; method relies on that feature and a recursive call to itself to build the collection of children for that new node with &lt;code&gt;Node.new(child.name, child.next_children)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Looking back at our &lt;code&gt;node&lt;/code&gt; method we&amp;rsquo;ll need to break the rules of East-oriented Code. Since we have immutable objects, we&amp;rsquo;ll return a new node instead of &lt;code&gt;self&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def node(name, &amp;amp;block)
  new_child = Node.new(name, &amp;amp;block)
  Node.new(self.name, next_children + [new_child])
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But there&amp;rsquo;s still a problem left. Because we need our initialized object to execute a block and the contstructor &lt;code&gt;new&lt;/code&gt; might actually need to return a different object than the one originally created. The call to &lt;code&gt;node&lt;/code&gt; inside the block changes the return value from the instance that &lt;code&gt;new&lt;/code&gt; creates, to the instance that &lt;code&gt;node&lt;/code&gt; creates.&lt;/p&gt;

&lt;h2&gt;Controlling the constructor&lt;/h2&gt;

&lt;p&gt;To better handle our immutable objects and the return values from the methods we created, we can alter the way the &lt;code&gt;new&lt;/code&gt; method works on our Node class.&lt;/p&gt;

&lt;p&gt;Instead of handling a block in the &lt;code&gt;initialize&lt;/code&gt; method, we can move it to &lt;code&gt;new&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Here&amp;rsquo;s the new &lt;code&gt;new&lt;/code&gt; method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def self.new(*args, &amp;amp;block)
  instance = super.freeze
  if block
    instance.instance_eval(&amp;amp;block)
  else
    instance
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The first step is to call &lt;code&gt;super&lt;/code&gt; to get an instance the way Ruby normally creates them (as defined in the super class of Node). Then we &lt;code&gt;freeze&lt;/code&gt; it.&lt;/p&gt;

&lt;p&gt;If we haven&amp;rsquo;t provided a block to the &lt;code&gt;new&lt;/code&gt; method, we&amp;rsquo;ll want to return the instance we just created. If we have provided a block, we&amp;rsquo;ll need to evaluate that block in the context of the instance we just created and return it&amp;rsquo;s result.&lt;/p&gt;

&lt;p&gt;This means that the block can use the &lt;code&gt;node&lt;/code&gt; method and whatever is returned by it.&lt;/p&gt;

&lt;p&gt;We need to alter the &lt;code&gt;new&lt;/code&gt; method this way because we&amp;rsquo;re not always just returning the instance it creates. Since our objects are frozen, we can&amp;rsquo;t allow the block to alter their states.&lt;/p&gt;

&lt;p&gt;The way &lt;code&gt;new&lt;/code&gt; &lt;em&gt;usually&lt;/em&gt; works is like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def self.new(*args, &amp;amp;block)
  instance = allocate
  instance.send(:initialize, *args, &amp;amp;block)
  return instance
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can see the reason that Ruby has you call &lt;code&gt;new&lt;/code&gt; on a class but in practice you write your &lt;code&gt;initialize&lt;/code&gt; method. This structure ensures that no matter the result of your &lt;code&gt;initialize&lt;/code&gt; method, &lt;code&gt;new&lt;/code&gt; will always return an instance of the class you&amp;rsquo;ve used.&lt;/p&gt;

&lt;p&gt;We&amp;rsquo;re bending the rules to allow us to evaluate the given block and return &lt;em&gt;its&lt;/em&gt; result, instead of the instance typically created by &lt;code&gt;new&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;After that, we can remove the block evaluation from &lt;code&gt;initialize&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def initialize(name, children=[])
  @name = name.freeze
  @children = children.freeze
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;While the method signature (the list of accepted arguments) has changed for &lt;code&gt;initialize&lt;/code&gt;, it&amp;rsquo;s still the same for &lt;code&gt;new&lt;/code&gt;: a list of arugments and a block.&lt;/p&gt;

&lt;p&gt;Believe it or not, there&amp;rsquo;s still one more problem to solve.&lt;/p&gt;

&lt;h2&gt;Operating on values&lt;/h2&gt;

&lt;p&gt;We looked at how returning &lt;code&gt;self&lt;/code&gt; allows you to chain your method calls. Although we&amp;rsquo;ve broken that rule and are instead returning a new Node object, it&amp;rsquo;s important to consider that chaining.&lt;/p&gt;

&lt;p&gt;Our initial code still doesn&amp;rsquo;t work quite right and it&amp;rsquo;s all because we need to think about operating on the return values of our commands and &lt;em&gt;not&lt;/em&gt; relying on an imperitive approach to building and &lt;em&gt;changing&lt;/em&gt; objects.&lt;/p&gt;

&lt;p&gt;First, here&amp;rsquo;s what our Node class looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Node
  def self.new(*args, &amp;amp;block)
    instance = super.freeze
    if block
      instance.instance_eval(&amp;amp;block)
    else
      instance
    end
  end

  def initialize(name, children=[])
    @name = name.freeze
    @children = children.freeze
  end

  attr_reader :children, :name

  def node(name, &amp;amp;block)
    new_child = self.class.new(name, &amp;amp;block)
    self.class.new(self.name, next_children + [new_child])
  end

  def next_children
    children.map{|child| self.class.new(child.name, child.next_children) }.freeze
  end

  def inspect
    return %{&quot;#{name}&quot;} if children.empty?
    %{&quot;#{name}&quot;, #{children}}
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We didn&amp;rsquo;t discuss it, but there&amp;rsquo;s an &lt;code&gt;inspect&lt;/code&gt; method to return either the name of the node if it has no children, or the name and a list of children if it has some.&lt;/p&gt;

&lt;p&gt;Here&amp;rsquo;s what the code to create the tree looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Node.new('root') do
  node('branch') do
    node('leaf')
    node('leaf2')
    node('leaf3')
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If we assign the result of that to a variable and inspect it we&amp;rsquo;ll get a surprising result.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;t = Node.new('root') do
      node('branch') do
        node('leaf')
        node('leaf2')
        node('leaf3')
      end
    end
puts [t].inspect
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The output will only be &lt;code&gt;[&quot;root&quot;, [&quot;branch&quot;, [&quot;leaf3&quot;]]]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;So what happened to the other &lt;code&gt;leaf&lt;/code&gt; and &lt;code&gt;leaf2&lt;/code&gt; objects? Why aren&amp;rsquo;t they there?&lt;/p&gt;

&lt;p&gt;Remember that each &lt;code&gt;node&lt;/code&gt; call returns a new node. With every &lt;code&gt;node&lt;/code&gt; a new result is returned. The &lt;code&gt;node('leaf')&lt;/code&gt; returns an object, but &lt;code&gt;node('leaf2')&lt;/code&gt; is not a message sent to the object returned by the first. It is a message sent to the &lt;code&gt;node('branch')&lt;/code&gt; result.&lt;/p&gt;

&lt;p&gt;Each of those calls is returned and forgotten. Here it is annotated:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;t = Node.new('root') do
      node('branch') do
        node('leaf') # returned and forgotten
        node('leaf2') # returned and forgotten
        node('leaf3') # returned and used as the final result
      end
    end
puts [t].inspect
#=&amp;gt; [&quot;root&quot;, [&quot;branch&quot;, [&quot;leaf3&quot;]]]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The answer to this problem is to command each object to do the next thing. We can achieve this by chaining the methods. The result of one method is the object which will receive the next command.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;t = Node.new('root') do
      node('branch') do
        node('leaf'). # dot (.) charater added to chain
        node('leaf2'). # executed on the result of the last node
        node('leaf3') # executed on the result of the last node
      end
    end
puts [t].inspect
#=&amp;gt; [&quot;root&quot;, [&quot;branch&quot;, [&quot;leaf&quot;, &quot;leaf2&quot;, &quot;leaf3&quot;]]]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;An alternative way to look at this is to store the result of each command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;t = Node.new('root') do
      node('branch') do
        branch = node('leaf')
        next_branch = branch.node('leaf2')
        final_branch = next_branch.node('leaf3')
      end
    end
puts [t].inspect
#=&amp;gt; [&quot;root&quot;, [&quot;branch&quot;, [&quot;leaf&quot;, &quot;leaf2&quot;, &quot;leaf3&quot;]]]
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Following the rules so you know when to break them&lt;/h2&gt;

&lt;p&gt;What was interesting about this to me was that my code was prepared for the immutable objects when I prepared it to operate on the same one. By structuring my code to return &lt;code&gt;self&lt;/code&gt; and send the next message to the result of the last, I was able to change the implementation from an imperative style to a functional style.&lt;/p&gt;

&lt;p&gt;&lt;form action=&quot;http://campaign.saturnflyer.com/t/r/s/fuitlt/&quot; method=&quot;post&quot; id=&quot;subForm&quot; style=&quot;background-color: #F7F1CD; border: 1px solid #999; padding: 1em;&quot;&gt;&lt;/p&gt;

&lt;h3&gt;Clean Up Your Code and get a Free chapter of Clean Ruby&lt;/h3&gt;


&lt;p&gt;If you liked this post and want more like it, get periodic tips in your inbox by leaving your email address below. &lt;img src=&quot;http://solarhost.s3.amazonaws.com/21/assets/58/book-shadow.png&quot; alt=&quot;Clean Ruby&quot; title=&quot;Get a Free sample chapter&quot; style=&quot;border:0 none;&quot; /&gt;&lt;/p&gt;


&lt;p&gt;To get more information about cleaning up your objects, classes, and code, then check out &lt;a href=&quot;http://clean-ruby.com&quot;&gt;Clean Ruby&lt;/a&gt;, an ebook which will describe ways to &lt;a href=&quot;http://www.clean-ruby.com/&quot;&gt;keep your code clean, maintainable, and focused on business value&lt;/a&gt;. Make your OOP more obvious, easier to understand, easier to test, and easier to maintain.&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;fuitlt-fuitlt&quot;&gt;Email: (required)&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-fuitlt-fuitlt&quot; id=&quot;fuitlt-fuitlt&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-name&quot; id=&quot;name&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;clear: both;&quot;&gt;
  &lt;input type=&quot;submit&quot; value=&quot;Subscribe for Ruby tips and a Free chapter!&quot; /&gt;&lt;/p&gt;


&lt;p&gt;&lt;/form&gt;&lt;/p&gt;</description>
      <pubDate>Wed, 19 Aug 2015 00:00:00 GMT</pubDate>
      <guid>http://www.saturnflyer.com/blog/jim/2015/08/19/commanding-objects-toward-immutability/</guid>
      <link>http://www.saturnflyer.com/blog/jim/2015/08/19/commanding-objects-toward-immutability/</link>
    </item>
  
    <item>
      <title>Cohesive behaviors with data clumps</title>
      <dc:creator>Angela</dc:creator>
      <description>&lt;p&gt;A good example of how we use context and locality to understand and manage concepts in our code is using a data clump.&lt;/p&gt;

&lt;p&gt;A data clump is a collection of two or more bits of information that are consistently used together. You’ll find that your data loses its meaning when you remove items from the clump.&lt;/p&gt;

&lt;p&gt;Date ranges are simple examples of how a data clump puts necessary information into context.
An example of this is to find out if a question was asked between today and one month ago. If our Question class implements a query method for this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Question
  def asked_within?(start_date, end_date)
    (start_date..end_date).cover?(self.asked_date)
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then we can pass in our desired dates to get the answer:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# using ActiveSupport
start_date = 1.month.ago
end_date = Time.now
question.asked_within?(start_date, end_date)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Discovering whether a question is within this time frame always requires both a start and end date. This is an indication that we can only understand the feature and indeed only implement it when we have this data clump. To better encapsulate the behavior of these values, we can create a class to manage initializing objects that represent them.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;DateRange = Struct.new(:start_date, :end_date)
last_month = DateRange.new(1.month.ago, Time.now)
question.asked_within?(last_month)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can then change our Question class to instead take a date range object for the asked_within? method, but the question’s responsibilities have grown a bit here. A question doesn’t have anything to do with comparing dates, so we can move the control of that information into the data clump that represents them.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;DateRange = Struct.new(:start_date, :end_date) do
  def contains?(date)
    (start_date..end_date).cover?(date)
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, instead of the question managing its date comparison, the date range can do the work.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;last_month.contains?(question.date_asked)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;By analyzing the individual parts of this date comparison we have to juggle a bit more in our heads. Considering a range as an complete object rather than a collection of parts is simpler and we tend not to think of every individual day within a month when doing a mental comparison. A date range is a small system of interacting parts that we better understand as a broader context.&lt;/p&gt;

&lt;p&gt;This example shows us the value not only of separating responsibilities, but of bringing objects together. We get more value by putting details into context than we would have if they remained separate.&lt;/p&gt;

&lt;h2&gt;Things to note&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;Struct.new&lt;/code&gt; returns a class instance. Inheriting from the result of a new Struct creates an anonymous class in the ancestors of your created class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[DateRange, #&amp;lt;Class:0x007f885d0be518&amp;gt;, Struct, ...]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Instead of &lt;code&gt;class DateRange &amp;lt; Struct.new; end&lt;/code&gt; use &lt;code&gt;DateRange = Struct.new&lt;/code&gt; and avoid an anonymous class in the ancestors:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[DateRange, Struct, ...]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Additionaly, be careful with large ranges. If our code used &lt;code&gt;include?&lt;/code&gt; instead of &lt;code&gt;cover?&lt;/code&gt;, Ruby would initialize a &lt;code&gt;Time&lt;/code&gt; object for every time between the beginning and end. As your range grows, the memory needed to calculate the answer will grow too.&lt;/p&gt;

&lt;p&gt;Avoid excessive memory and use &lt;code&gt;cover?&lt;/code&gt; instead. It will check that your beginning date is less than or equal to the given date, and that the given date is less than or equal to the end date.&lt;/p&gt;

&lt;p&gt;This article is an excerpt from my book &lt;a href=&quot;http://clean-ruby.com&quot;&gt;Clean Ruby&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;form action=&quot;http://campaign.saturnflyer.com/t/r/s/fuitlt/&quot; method=&quot;post&quot; id=&quot;subForm&quot; style=&quot;background-color: #F7F1CD; border: 1px solid #999; padding: 1em;&quot;&gt;&lt;/p&gt;

&lt;h3&gt;Clean Up Your Code and get a Free chapter of Clean Ruby&lt;/h3&gt;


&lt;p&gt;If you liked this post and want more like it, get periodic tips in your inbox by leaving your email address below. &lt;img src=&quot;http://solarhost.s3.amazonaws.com/21/assets/58/book-shadow.png&quot; alt=&quot;Clean Ruby&quot; title=&quot;Get a Free sample chapter&quot; style=&quot;border:0 none;&quot; /&gt;&lt;/p&gt;


&lt;p&gt;To get more information about cleaning up your objects, classes, and code, then check out &lt;a href=&quot;http://clean-ruby.com&quot;&gt;Clean Ruby&lt;/a&gt;, an ebook which will describe ways to &lt;a href=&quot;http://www.clean-ruby.com/&quot;&gt;keep your code clean, maintainable, and focused on business value&lt;/a&gt;. Make your OOP more obvious, easier to understand, easier to test, and easier to maintain.&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;fuitlt-fuitlt&quot;&gt;Email: (required)&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-fuitlt-fuitlt&quot; id=&quot;fuitlt-fuitlt&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-name&quot; id=&quot;name&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;clear: both;&quot;&gt;
  &lt;input type=&quot;submit&quot; value=&quot;Subscribe for Ruby tips and a Free chapter!&quot; /&gt;&lt;/p&gt;


&lt;p&gt;&lt;/form&gt;&lt;/p&gt;</description>
      <pubDate>Thu, 30 Apr 2015 00:00:00 GMT</pubDate>
      <guid>http://www.saturnflyer.com/blog/jim/2015/04/30/cohesive-behaviors-with-data-clumps/</guid>
      <link>http://www.saturnflyer.com/blog/jim/2015/04/30/cohesive-behaviors-with-data-clumps/</link>
    </item>
  
    <item>
      <title>The difference between instance_eval and instance_exec</title>
      <dc:creator>Angela</dc:creator>
      <description>&lt;p&gt;There&amp;rsquo;s an important difference between &lt;code&gt;instance_eval&lt;/code&gt; and &lt;code&gt;instance_exec&lt;/code&gt;. And there&amp;rsquo;s a great lesson about how to use them well in &lt;a href=&quot;https://github.com/thoughtbot/factory_girl&quot;&gt;FactoryGirl&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But first, before you go &lt;a href=&quot;http://clean-ruby.com/dsl&quot;&gt;rushing off to build your fantastic DSL&lt;/a&gt;, let&amp;rsquo;s look at what &lt;code&gt;instance_eval&lt;/code&gt; is and does.&lt;/p&gt;

&lt;p&gt;The simplest of examples can be taken straight from the Ruby docs:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class KlassWithSecret
  def initialize
    @secret = 99
  end
end
k = KlassWithSecret.new
k.instance_eval { @secret } #=&amp;gt; 99
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The current value for &lt;code&gt;self&lt;/code&gt; inside the provided block will be the object on which you call &lt;code&gt;instance_eval&lt;/code&gt;. So in this case the &lt;code&gt;k&lt;/code&gt; object is the current context for the block; &lt;code&gt;@secret&lt;/code&gt; is a variable stored inside &lt;code&gt;k&lt;/code&gt; and &lt;code&gt;instance_eval&lt;/code&gt; opens up access to that object and all of it&amp;rsquo;s internal variables.&lt;/p&gt;

&lt;p&gt;The interface that FactoryGirl provides is simple and straightforward. Here&amp;rsquo;s an example from it&amp;rsquo;s &amp;ldquo;Getting Started&amp;rdquo; documentation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;FactoryGirl.define do
  factory :user do
    first_name &quot;Kristoff&quot;
    last_name  &quot;Bjorgman&quot;
    admin false
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here, FactoryGirl uses &lt;code&gt;instance_eval&lt;/code&gt; to execute the blocks of code passed to &lt;code&gt;factory&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let&amp;rsquo;s take a look at some representative code from how FactoryGirl makes this work:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def factory(name, &amp;amp;block)
  factory = Factory.new(name)
  factory.instance_eval(&amp;amp;block) if block_given?
  # ... more code
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&amp;rsquo;s not actually the code from FactoryGirl, but it represents roughly what happens. When the method &lt;code&gt;factory&lt;/code&gt; is called a new &lt;code&gt;Factory&lt;/code&gt; is created and then the block is executed in the context of that object. In other words where you see &lt;code&gt;first_name&lt;/code&gt; it&amp;rsquo;s as if you had that factory instance before it and instead had &lt;code&gt;factory.first_name&lt;/code&gt;. By using &lt;code&gt;instance_eval&lt;/code&gt;, the users of FactoryGirl don&amp;rsquo;t need to specify the factory object, it&amp;rsquo;s implicitly applied to it.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Ok, that&amp;rsquo;s all well and good, but what about &lt;code&gt;instance_exec&lt;/code&gt;?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I&amp;rsquo;m glad you asked.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;instance_eval&lt;/code&gt; method can only evaluate a block (or a string) but that&amp;rsquo;s it. Need to pass arguments into the block? You&amp;rsquo;ll be frozen in your tracks.&lt;/p&gt;

&lt;p&gt;But &lt;code&gt;instance_exec&lt;/code&gt; on the other hand, will evaluate a provide block &lt;strong&gt;and&lt;/strong&gt; allow you to pass arguments to it. Let&amp;rsquo;s take a look&amp;hellip;&lt;/p&gt;

&lt;p&gt;FactoryGirl allows you to handle callbacks to perform some action, for example, after the object is created.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;FactoryGirl.define do
  factory :user do
    first_name &quot;Kristoff&quot;
    last_name &quot;Bjorgman&quot;
    admin false

    after(:create) do |user, evaluator|
      create_list(:post, evaluator.posts_count, user: user)
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this sample, the &lt;code&gt;after(:create)&lt;/code&gt; is run after the object is created, but the block accepts two arguments: &lt;code&gt;user&lt;/code&gt; and &lt;code&gt;evaluator&lt;/code&gt;. The &lt;code&gt;user&lt;/code&gt; argument is the user that was created. The &lt;code&gt;evaluator&lt;/code&gt; is an object which stores all the values created by the factory.&lt;/p&gt;

&lt;p&gt;Let&amp;rsquo;s take a look at how this is implemented:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def run(instance, evaluator)
  case block.arity
  when 1, -1 then syntax_runner.instance_exec(instance, &amp;amp;block)
  when 2 then syntax_runner.instance_exec(instance, evaluator, &amp;amp;block)
  else        syntax_runner.instance_exec(&amp;amp;block)
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;FactoryGirl will create a callback object named by the argument given to the &lt;code&gt;after&lt;/code&gt; method. The callback is created with a name, &lt;code&gt;:create&lt;/code&gt; in this case, and with a block of code.&lt;/p&gt;

&lt;p&gt;The block that we used in our example had two arguments.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;run&lt;/code&gt; method decides how to execute the code from the block.&lt;/p&gt;

&lt;p&gt;The callback object stores the provided block and Ruby allows us to check the arity of the block, or in other words, it allows us to check the number of arguments.&lt;/p&gt;

&lt;p&gt;When looking at a &lt;code&gt;case&lt;/code&gt; statement, it&amp;rsquo;s a good idea to check the &lt;code&gt;else&lt;/code&gt; clause first. This gives you an idea of what will happen if there&amp;rsquo;s no match for whatever code exists in the &lt;code&gt;when&lt;/code&gt; parts.&lt;/p&gt;

&lt;p&gt;There we see &lt;code&gt;syntax_runner.instance_exec(&amp;amp;block)&lt;/code&gt; and this could easily be changed to use &lt;code&gt;instance_eval&lt;/code&gt; instead. Ruby will evaluate, or execute, the block in the context of the &lt;code&gt;syntax_runner&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;If the block&amp;rsquo;s arity is greater than zero, FactoryGirl needs to provide the objects to the block so that our code works the way we expect.&lt;/p&gt;

&lt;p&gt;The second part of the case checks if the block arity is equal to &lt;code&gt;2&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;when 2 then syntax_runner.instance_exec(instance, evaluator, &amp;amp;block)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If it is, the &lt;code&gt;syntax_runner&lt;/code&gt; receives the &lt;code&gt;instance&lt;/code&gt; (or in our case &lt;code&gt;user&lt;/code&gt;) and the &lt;code&gt;evaluator&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If, however, the arity is &lt;code&gt;1&lt;/code&gt; or &lt;code&gt;-1&lt;/code&gt; then the block will only receive the &lt;code&gt;instance&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;So what is that &lt;code&gt;-1&lt;/code&gt; value? Let&amp;rsquo;s look at the ways we &lt;em&gt;could&lt;/em&gt; create a callback:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Two arguments and arity of 2
after(:create) do |user, evaluator|
  create_list(:post, evaluator.posts_count, user: user)
end
# One argument and arity of 1
after(:create) do |user|
  create_group(:people, user: user)
end
# Zero arguments and arity of 0
after(:create) do
  puts &quot;Yay!&quot;
end
# Any arguments and arity of -1
after(:create) do |*args|
  puts &quot;The user is #{args.first}&quot;
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Ruby doesn&amp;rsquo;t know how many &lt;code&gt;args&lt;/code&gt; you&amp;rsquo;ll give it with &lt;code&gt;*args&lt;/code&gt; so it throws up it&amp;rsquo;s hands and tells you that it&amp;rsquo;s some strange number: &lt;code&gt;-1&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This is the power of understanding how and when to use &lt;code&gt;instance_exec&lt;/code&gt;; users of the DSL will expect it to make sense, and it will.&lt;/p&gt;

&lt;p&gt;But wait! There&amp;rsquo;s more!&lt;/p&gt;

&lt;p&gt;What if you want to specify the same value for multiple attributes?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;FactoryGirl.define do
  factory :user do
    first_name &quot;Kristoff&quot;
    last_name  &quot;Bjorgman&quot;

    password &quot;12345&quot;
    password_confirmation &quot;12345&quot;
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the above example, both the &lt;code&gt;password&lt;/code&gt; and &lt;code&gt;password_confirmation&lt;/code&gt; are set to the same value. This could be bad.
What if you change the password for one, but forget to change the other? If they are inherently tied in their implementation, then that could lead to some unexpected behavior when they are not the same.&lt;/p&gt;

&lt;p&gt;I would, and probably you would too, prefer to tell FactoryGirl to just use the value I&amp;rsquo;d already configured.&lt;/p&gt;

&lt;p&gt;Fortunately FactoryGirl allows us to use a great trick in Ruby using the &lt;code&gt;to_proc&lt;/code&gt; method. Here&amp;rsquo;s what it looks like in use:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;FactoryGirl.define do
  factory :user do
    first_name &quot;Kristoff&quot;
    last_name  &quot;Bjorgman&quot;

    password &quot;12345&quot;
    password_confirmation &amp;amp;:password
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The important part is the &lt;code&gt;&amp;amp;:password&lt;/code&gt; value provided to &lt;code&gt;password_confirmation&lt;/code&gt;. Ruby will see the &lt;code&gt;&amp;amp;&lt;/code&gt; character and treat the following as a block by calling &lt;code&gt;to_proc&lt;/code&gt; on it. To implement this feature, FactoryGirl defines &lt;code&gt;to_proc&lt;/code&gt; on attributes and there will use &lt;code&gt;instance_exec&lt;/code&gt; to provide the symbol &lt;code&gt;password&lt;/code&gt; to the block:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def to_proc
  block = @block

  -&amp;gt; {
    value = case block.arity
            when 1, -1 then instance_exec(self, &amp;amp;block)
            else instance_exec(&amp;amp;block)
            end
    raise SequenceAbuseError if FactoryGirl::Sequence === value
    value
  }
end
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;What about lambdas and procs?&lt;/h3&gt;

&lt;p&gt;Some commenters in Reddit raised an important question about how these methods behave when given lambdas and procs.&lt;/p&gt;

&lt;p&gt;If you provide a lambda which accepts no arguments as the block, &lt;code&gt;instance_eval&lt;/code&gt; will raise an error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;object = Object.new
argless = -&amp;gt;{ puts &quot;foo&quot; }
object.instance_eval(&amp;amp;argless) #=&amp;gt; ArgumentError: wrong number of arguments (1 for 0)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This error occurs because Ruby will yield the current object to the provided block as &lt;code&gt;self&lt;/code&gt;. So you can fix it by providing a lambda which accepts an argument:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;args = -&amp;gt;(obj){ puts &quot;foo&quot; }
object.instance_eval(&amp;amp;args) #=&amp;gt; &quot;foo&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This changes a bit if you use &lt;code&gt;instance_exec&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;object.instance_exec(&amp;amp;argless) #=&amp;gt; &quot;foo&quot;
object.instance_exec(&amp;amp;args) #=&amp;gt; ArgumentError: wrong number of arguments (0 for 1)
object.instance_exec(&quot;some argument&quot;, &amp;amp;args) #=&amp;gt; &quot;foo&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Because a &lt;code&gt;proc&lt;/code&gt; is less restrictive with argument requirements, it will allow either approach to work without error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;p_argless = proc{ puts &quot;foo&quot; }
object.instance_eval(&amp;amp;p_argless) #=&amp;gt; &quot;foo&quot;

p_args = proc{|obj| puts &quot;foo&quot; }
object.instance_eval(&amp;amp;p_args) #=&amp;gt; &quot;foo&quot;

object.instance_exec(&amp;amp;p_args) #=&amp;gt; &quot;foo&quot;
object.instance_exec(&amp;amp;p_argless) #=&amp;gt; &quot;foo&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now you know, &lt;code&gt;instance_exec&lt;/code&gt; and &lt;code&gt;instance_eval&lt;/code&gt; are similar in the way they behave, but you&amp;rsquo;ll reach for &lt;code&gt;instance_exec&lt;/code&gt; if you need to pass variables around.&lt;/p&gt;

&lt;h2&gt;Announcing Ruby Metaprogramming Masterclass&lt;/h2&gt;

&lt;p&gt;I&amp;rsquo;m offering a new online class where I&amp;rsquo;ll be teaching you how to master metaprogramming in Ruby on April 30th (the day after my birthday!)&lt;/p&gt;

&lt;p&gt;I&amp;rsquo;m keeping the spaces limited to 25 so attendees will be able to talk and ask questions but already over a quarter of the seats are gone. &lt;a href=&quot;http://clean-ruby.com/metaprogramming&quot;&gt; So grab a seat now&lt;/a&gt;, before they&amp;rsquo;re all gone.&lt;/p&gt;

&lt;p&gt;&lt;form action=&quot;http://campaign.saturnflyer.com/t/r/s/fuitlt/&quot; method=&quot;post&quot; id=&quot;subForm&quot; style=&quot;background-color: #F7F1CD; border: 1px solid #999; padding: 1em;&quot;&gt;&lt;/p&gt;

&lt;h3&gt;Clean Up Your Code and get a Free chapter of Clean Ruby&lt;/h3&gt;


&lt;p&gt;If you liked this post and want more like it, get periodic tips in your inbox by leaving your email address below. &lt;img src=&quot;http://solarhost.s3.amazonaws.com/21/assets/58/book-shadow.png&quot; alt=&quot;Clean Ruby&quot; title=&quot;Get a Free sample chapter&quot; style=&quot;border:0 none;&quot; /&gt;&lt;/p&gt;


&lt;p&gt;To get more information about cleaning up your objects, classes, and code, then check out &lt;a href=&quot;http://clean-ruby.com&quot;&gt;Clean Ruby&lt;/a&gt;, an ebook which will describe ways to &lt;a href=&quot;http://www.clean-ruby.com/&quot;&gt;keep your code clean, maintainable, and focused on business value&lt;/a&gt;. Make your OOP more obvious, easier to understand, easier to test, and easier to maintain.&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;fuitlt-fuitlt&quot;&gt;Email: (required)&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-fuitlt-fuitlt&quot; id=&quot;fuitlt-fuitlt&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-name&quot; id=&quot;name&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;clear: both;&quot;&gt;
  &lt;input type=&quot;submit&quot; value=&quot;Subscribe for Ruby tips and a Free chapter!&quot; /&gt;&lt;/p&gt;


&lt;p&gt;&lt;/form&gt;&lt;/p&gt;</description>
      <pubDate>Wed, 22 Apr 2015 00:00:00 GMT</pubDate>
      <guid>http://www.saturnflyer.com/blog/jim/2015/04/22/the-difference-between-instance_eval-and-instance_exec/</guid>
      <link>http://www.saturnflyer.com/blog/jim/2015/04/22/the-difference-between-instance_eval-and-instance_exec/</link>
    </item>
  
    <item>
      <title>Locality and Cohesion</title>
      <dc:creator>Angela</dc:creator>
      <description>&lt;blockquote&gt;&lt;p&gt;&amp;ldquo;The primary feature for easy maintenance is locality: Locality is that characteristic of source code that enables a programmer to understand that source by looking at only a small portion of it.&amp;rdquo; &amp;mdash; Richard Gabriel&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;This advice is from &lt;a href=&quot;https://www.dreamsongs.com/Files/PatternsOfSoftware.pdf&quot;&gt;Patterns of Software&lt;/a&gt; by Richard Gabriel.&lt;/p&gt;

&lt;p&gt;Keeping cohesive parts of our system together can help us understand it. By managing locality we can keep cohesive parts together.&lt;/p&gt;

&lt;p&gt;It’s easy to see coupling in our code. When one object can&amp;rsquo;t do it&amp;rsquo;s job without another, we experience frustration in the face of change. We often think about dependencies in our code, but cohesion is the relatedness of the behaviors and plays an import part in how we organize the ideas to support our domain.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def process_payment(amount)
  gateway.authorize_and_charge(amount) do
    deliver_cart
  end
  logger.info &quot;handling payment: #{amount}&quot;
  logger.info &quot;cart delivered: #{id}&quot;
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The exact purpose of this completely-made-up code isn&amp;rsquo;t that important. But we can look at parts of this procedure and extract them into a related method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def process_payment(amount)
  gateway.authorize_and_charge(amount) do
    deliver_cart
  end
  log_purchase(amount)
end

def log_purchase(amount)
  logger.info &quot;handling payment: #{amount}&quot;
  logger.info &quot;cart delivered: #{id}&quot;
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As Gabriel points out in his book, we can compress a procedure into a simple phrase like &lt;code&gt;log_purchase&lt;/code&gt; but this compression carries a cost. In order to understand the behavior of this &lt;code&gt;log_purchase&lt;/code&gt; phrase, we need to understand the context around it.&lt;/p&gt;

&lt;p&gt;Indeed, we might look at this and realize that there&amp;rsquo;s a problem with the way we managed the locality of the procedure. Instead of easily understanding a single method, we might look at &lt;code&gt;process_payment&lt;/code&gt; and realize there&amp;rsquo;s a bit more to it than we first expect.&lt;/p&gt;

&lt;p&gt;We&amp;rsquo;re forced to understand the &lt;code&gt;log_purchase&lt;/code&gt; &lt;strong&gt;and&lt;/strong&gt; the context which previously surrounded it&amp;rsquo;s procedure. A second look at this extraction might lead us to reconsider and to go back to inline the method. Let&amp;rsquo;s keep this code with a tighter locality:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def process_payment(amount)
  gateway.authorize_and_charge(amount) do
    deliver_cart
  end
  logger.info &quot;handling payment: #{amount}&quot;
  logger.info &quot;cart delivered: #{id}&quot;
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;While extracting the &lt;code&gt;log_purchase&lt;/code&gt; method was easy, given the original code, it added a bit too much for us to understand and it doesn&amp;rsquo;t feel quite right. Handling the locality of this code helps us to better understand it and to make better decisions about how to improve the main &lt;code&gt;process_payment&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;Consider this: How much must you pack into your head before you can begin evaluating a part of your code?&lt;/p&gt;

&lt;p&gt;While breaking procedures up into small methods can be a useful way to make easy to understand (and easy to test) parts, we may do so to the detriment of understanding.&lt;/p&gt;

&lt;p&gt;This is something to consider if you are &lt;a href=&quot;http://clean-ruby.com/dsl&quot;&gt;building a DSL&lt;/a&gt; to compress ideas in your code or if you&amp;rsquo;re trying to &lt;a href=&quot;http://clean-ruby.com&quot;&gt;create objects to manage your business logic&lt;/a&gt;. I&amp;rsquo;ll be writing more about the value of controlling the locality of behavior in your system, but I&amp;rsquo;d love to hear how you manage locality. What do you do to ensure that related bits stay together?&lt;/p&gt;

&lt;p&gt;&lt;form action=&quot;http://campaign.saturnflyer.com/t/r/s/fuitlt/&quot; method=&quot;post&quot; id=&quot;subForm&quot; style=&quot;background-color: #F7F1CD; border: 1px solid #999; padding: 1em;&quot;&gt;&lt;/p&gt;

&lt;h3&gt;Clean Up Your Code and get a Free chapter of Clean Ruby&lt;/h3&gt;


&lt;p&gt;If you liked this post and want more like it, get periodic tips in your inbox by leaving your email address below. &lt;img src=&quot;http://solarhost.s3.amazonaws.com/21/assets/58/book-shadow.png&quot; alt=&quot;Clean Ruby&quot; title=&quot;Get a Free sample chapter&quot; style=&quot;border:0 none;&quot; /&gt;&lt;/p&gt;


&lt;p&gt;To get more information about cleaning up your objects, classes, and code, then check out &lt;a href=&quot;http://clean-ruby.com&quot;&gt;Clean Ruby&lt;/a&gt;, an ebook which will describe ways to &lt;a href=&quot;http://www.clean-ruby.com/&quot;&gt;keep your code clean, maintainable, and focused on business value&lt;/a&gt;. Make your OOP more obvious, easier to understand, easier to test, and easier to maintain.&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;fuitlt-fuitlt&quot;&gt;Email: (required)&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-fuitlt-fuitlt&quot; id=&quot;fuitlt-fuitlt&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-name&quot; id=&quot;name&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;clear: both;&quot;&gt;
  &lt;input type=&quot;submit&quot; value=&quot;Subscribe for Ruby tips and a Free chapter!&quot; /&gt;&lt;/p&gt;


&lt;p&gt;&lt;/form&gt;&lt;/p&gt;</description>
      <pubDate>Tue, 21 Apr 2015 00:00:00 GMT</pubDate>
      <guid>http://www.saturnflyer.com/blog/jim/2015/04/21/locality-and-cohesion/</guid>
      <link>http://www.saturnflyer.com/blog/jim/2015/04/21/locality-and-cohesion/</link>
    </item>
  
    <item>
      <title>The 4 Rules of East-oriented Code: Rule 4</title>
      <dc:creator>Angela</dc:creator>
      <description>&lt;p&gt;Often the rules we create are defined by their exceptions.&lt;/p&gt;

&lt;p&gt;It is difficult to create a program which continually passes objects and never returns data. Often the first rule of &amp;ldquo;Always return self&amp;rdquo; is met with immediate rejection because it&amp;rsquo;s easy to see the difficulty you&amp;rsquo;d encounter if that rule is continually followed for every object.&lt;/p&gt;

&lt;p&gt;In &lt;a href=&quot;http://confreaks.com/videos/4825-RubyConf2014-eastward-ho-a-clear-path-through-ruby-with-oo&quot;&gt;my presentation for RubyConf&lt;/a&gt;, I showed how we break the rules to allow value objects to handle data for a template. I &lt;a href=&quot;http://www.saturnflyer.com/blog/jim/2014/12/16/preferring-value-objects-or-setters-and-arguments/&quot;&gt;previously wrote&lt;/a&gt; about the approach I used in the presentation to push data into a value object.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Address
  def display(template)
    if protect_privacy?
      template.display_address(private_version)
    else
      template.display_address(public_version)
    end
    self
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the sample above, an Address instance commands a template to &lt;code&gt;display_address&lt;/code&gt; with different versions of data: &lt;code&gt;private_version&lt;/code&gt; or &lt;code&gt;public_version&lt;/code&gt;. This makes a flexible interface that allows &lt;code&gt;Address&lt;/code&gt; to create any number of different versions if necessary. Perhaps the requirements will demand a &lt;code&gt;semi_public_version&lt;/code&gt; in the future; our design of the template need not change.&lt;/p&gt;

&lt;p&gt;This is a great way to break the rules. Value objects allow us to parameterize a collection of data in a single object. The alternative to this approach would be to use setter methods on the template object:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Address
  def display(template)
    unless protect_privacy?
      template.street = street
      template.apartment = apartment
      template.postal_code = postal_code
    end
    template.city = city
    template.province = province
    template.display_address
    self
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can plainly see that although the code follows the rules by commanding the template object, there&amp;rsquo;s also quite a lot happening in this &lt;code&gt;display&lt;/code&gt; method on &lt;code&gt;Address&lt;/code&gt;. If the requirements change we might feel encouraged to complicate the &lt;code&gt;unless&lt;/code&gt; block or &amp;ldquo;refactor&amp;rdquo; it into a &lt;code&gt;case&lt;/code&gt; statement. While that might solve our problem, the resulting code could lead to some difficult to read and understand implementation details.&lt;/p&gt;

&lt;p&gt;By breaking the rules with a value object we can better encapsulate the ideas in a private address object or public or any other type we desire.&lt;/p&gt;

&lt;p&gt;But we&amp;rsquo;re not just breaking the rules inside the &lt;code&gt;Address&lt;/code&gt; methods; the template breaks the rules too. Rule 2 says that &lt;code&gt;objects may query themselves&lt;/code&gt; and subsequently means they should not query other objects. But by choosing to break the rules we make a design decision at a specific location to make things better.&lt;/p&gt;

&lt;p&gt;No matter what rules you follow, you decide not only to follow them, but decide to break them as well. To make your program easy to understand and to create reasonable expectations, you can lean on creating barriers. Preventing yourself from doing one thing frees you to do another.&lt;/p&gt;

&lt;p&gt;Embrace constraints.&lt;/p&gt;

&lt;p&gt;How do you add constraints to your programs? What are you better able to do by adding restrictions?&lt;/p&gt;

&lt;p&gt;&lt;form action=&quot;http://campaign.saturnflyer.com/t/r/s/fuitlt/&quot; method=&quot;post&quot; id=&quot;subForm&quot; style=&quot;background-color: #F7F1CD; border: 1px solid #999; padding: 1em;&quot;&gt;&lt;/p&gt;

&lt;h3&gt;Clean Up Your Code and get a Free chapter of Clean Ruby&lt;/h3&gt;


&lt;p&gt;If you liked this post and want more like it, get periodic tips in your inbox by leaving your email address below. &lt;img src=&quot;http://solarhost.s3.amazonaws.com/21/assets/58/book-shadow.png&quot; alt=&quot;Clean Ruby&quot; title=&quot;Get a Free sample chapter&quot; style=&quot;border:0 none;&quot; /&gt;&lt;/p&gt;


&lt;p&gt;To get more information about cleaning up your objects, classes, and code, then check out &lt;a href=&quot;http://clean-ruby.com&quot;&gt;Clean Ruby&lt;/a&gt;, an ebook which will describe ways to &lt;a href=&quot;http://www.clean-ruby.com/&quot;&gt;keep your code clean, maintainable, and focused on business value&lt;/a&gt;. Make your OOP more obvious, easier to understand, easier to test, and easier to maintain.&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;fuitlt-fuitlt&quot;&gt;Email: (required)&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-fuitlt-fuitlt&quot; id=&quot;fuitlt-fuitlt&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-name&quot; id=&quot;name&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;clear: both;&quot;&gt;
  &lt;input type=&quot;submit&quot; value=&quot;Subscribe for Ruby tips and a Free chapter!&quot; /&gt;&lt;/p&gt;


&lt;p&gt;&lt;/form&gt;&lt;/p&gt;</description>
      <pubDate>Tue, 07 Apr 2015 00:00:00 GMT</pubDate>
      <guid>http://www.saturnflyer.com/blog/jim/2015/04/07/the-4-rules-of-east-oriented-code-rule-4/</guid>
      <link>http://www.saturnflyer.com/blog/jim/2015/04/07/the-4-rules-of-east-oriented-code-rule-4/</link>
    </item>
  
    <item>
      <title>The 4 Rules of East-oriented Code: Rule 3</title>
      <dc:creator>Angela</dc:creator>
      <description>&lt;p&gt;When I set out to create &lt;a href=&quot;http://confreaks.com/videos/4825-RubyConf2014-eastward-ho-a-clear-path-through-ruby-with-oo&quot;&gt;my presentation for RubyConf&lt;/a&gt;, I wanted to provide the audience with something they could easily try. By doing that, one could walk away and put themselves in a position to think about their code differently. While, James Ladd, the creator of East-oriented Code made some basic rules, I decide to take them and frame it in the specific context of Ruby:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Always return self&lt;/li&gt;
&lt;li&gt;Objects may query themselves&lt;/li&gt;
&lt;li&gt;Factories are exempt&lt;/li&gt;
&lt;li&gt;Break the rules sparingly&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;After writing about &lt;a href=&quot;http://www.saturnflyer.com/blog/jim/2015/02/10/the-4-rules-of-east-oriented-code-rule-1/&quot;&gt;Rule 1&lt;/a&gt; and &lt;a href=&quot;http://www.saturnflyer.com/blog/jim/2015/03/10/the-4-rules-of-east-oriented-code-rule-2/&quot;&gt;Rule 2&lt;/a&gt; I&amp;rsquo;m very eager to get to Rule 3. It&amp;rsquo;s an easy way to break the intent of this style without breaking the rules.&lt;/p&gt;

&lt;h2&gt;Factories are Exempt&lt;/h2&gt;

&lt;p&gt;They must be. If you returned &lt;code&gt;self&lt;/code&gt; from &lt;code&gt;Object.new&lt;/code&gt; you&amp;rsquo;d just get &lt;code&gt;Object&lt;/code&gt; back, not an instance of an object. So factories are exempt from returning &lt;code&gt;self&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The best way to get around any of these rules is to just make something into a factory. But here lies the danger.
It&amp;rsquo;s important to first think about what these objects are doing. For what are they responsible?&lt;/p&gt;

&lt;p&gt;We could create a class to sweep our messy code under the rug.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;user = User.new
signup = UserSignupProcess.new
signup.create_with(user)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The code above, we could say, is East-oriented. The factories create instances, and the &lt;code&gt;signup&lt;/code&gt; object is told to &lt;code&gt;create_with&lt;/code&gt; and given the &lt;code&gt;user&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;Beyond this (inside &lt;code&gt;create_with&lt;/code&gt;), it could easily be an enormous mess. While we can and probably should use different programming techniques for different situations, taking a load of &lt;code&gt;if&lt;/code&gt; statements and sweeping it into a class could still be problematic.&lt;/p&gt;

&lt;p&gt;Now, the sample code above is completely made up to show how you can take part of your program and say &amp;ldquo;this part is East-oriented, but over here I used this other technique. I call it If-oriented.&amp;rdquo;&lt;/p&gt;

&lt;p&gt;Examining your domain and creating a program to support it requires that you carefully evaluate what objects should exist, what their responsibilities are, and what you will name them.&lt;/p&gt;

&lt;p&gt;East-orientation is all about designating responsibilities.&lt;/p&gt;

&lt;p&gt;This leads us to breaking the rules&amp;hellip;&lt;/p&gt;

&lt;p&gt;We&amp;rsquo;ll be getting to that later. There&amp;rsquo;s likely very good reasons to break any particular programming rule, but it probably depends on the context.&lt;/p&gt;

&lt;p&gt;I wrote &lt;a href=&quot;http://clean-ruby.com&quot;&gt;Clean Ruby&lt;/a&gt; and the chapter on East-oriented Code before I set up the 4 rules for my presentation, but the same lessons are there. I&amp;rsquo;ll be adding more to it, particularly as discussion and ideas around DCI evolve, but I&amp;rsquo;m putting effort toward wrapping up the &lt;a href=&quot;http://clean-ruby.com/dsl&quot;&gt;Ruby DSL Handbook&lt;/a&gt;. It will soon be complete and the $12 price will go up to $24, so pick it up now if you&amp;rsquo;re interested.&lt;/p&gt;

&lt;p&gt;Ruby DSL Handbook is about how to create a DSL without headaches from metaprogramming and I just released an update with a chapter about creating a DSL without metaprogramming at all. Much like this discussion today, it&amp;rsquo;s all about managing responsibilities.&lt;/p&gt;

&lt;p&gt;&lt;form action=&quot;http://campaign.saturnflyer.com/t/r/s/fuitlt/&quot; method=&quot;post&quot; id=&quot;subForm&quot; style=&quot;background-color: #F7F1CD; border: 1px solid #999; padding: 1em;&quot;&gt;&lt;/p&gt;

&lt;h3&gt;Clean Up Your Code and get a Free chapter of Clean Ruby&lt;/h3&gt;


&lt;p&gt;If you liked this post and want more like it, get periodic tips in your inbox by leaving your email address below. &lt;img src=&quot;http://solarhost.s3.amazonaws.com/21/assets/58/book-shadow.png&quot; alt=&quot;Clean Ruby&quot; title=&quot;Get a Free sample chapter&quot; style=&quot;border:0 none;&quot; /&gt;&lt;/p&gt;


&lt;p&gt;To get more information about cleaning up your objects, classes, and code, then check out &lt;a href=&quot;http://clean-ruby.com&quot;&gt;Clean Ruby&lt;/a&gt;, an ebook which will describe ways to &lt;a href=&quot;http://www.clean-ruby.com/&quot;&gt;keep your code clean, maintainable, and focused on business value&lt;/a&gt;. Make your OOP more obvious, easier to understand, easier to test, and easier to maintain.&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;fuitlt-fuitlt&quot;&gt;Email: (required)&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-fuitlt-fuitlt&quot; id=&quot;fuitlt-fuitlt&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-name&quot; id=&quot;name&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;clear: both;&quot;&gt;
  &lt;input type=&quot;submit&quot; value=&quot;Subscribe for Ruby tips and a Free chapter!&quot; /&gt;&lt;/p&gt;


&lt;p&gt;&lt;/form&gt;&lt;/p&gt;</description>
      <pubDate>Tue, 17 Mar 2015 00:00:00 GMT</pubDate>
      <guid>http://www.saturnflyer.com/blog/jim/2015/03/17/the-4-rules-of-east-oriented-code-rule-3/</guid>
      <link>http://www.saturnflyer.com/blog/jim/2015/03/17/the-4-rules-of-east-oriented-code-rule-3/</link>
    </item>
  
    <item>
      <title>The 4 Rules of East-oriented Code: Rule 2</title>
      <dc:creator>Jim Gay</dc:creator>
      <description>&lt;p&gt;In a previous article I wrote about &lt;a href=&quot;http://www.saturnflyer.com/blog/jim/2015/02/10/the-4-rules-of-east-oriented-code-rule-1/&quot;&gt;the first rule of East-oriented Code&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Here again are the rules I set forth in my presentation at &lt;a href=&quot;http://confreaks.com/videos/4825-RubyConf2014-eastward-ho-a-clear-path-through-ruby-with-oo&quot;&gt;RubyConf&lt;/a&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Always return self&lt;/li&gt;
&lt;li&gt;Objects may query themselves&lt;/li&gt;
&lt;li&gt;Factories are exempt&lt;/li&gt;
&lt;li&gt;Break the rules sparingly&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;The second rule, that &amp;ldquo;Objects may query themselves&amp;rdquo;, allows the design of objects to work with their own attributes.&lt;/p&gt;

&lt;p&gt;When we design our systems of interacting objects we can use the &lt;a href=&quot;https://pragprog.com/articles/tell-dont-ask&quot;&gt;Tell, Don&amp;rsquo;t Ask&lt;/a&gt; approach to limit the decisions in the code to objects which are responsible for the data used to make them.&lt;/p&gt;

&lt;p&gt;The Tell, Don&amp;rsquo;t Ask article begins by quoting Alec Sharp:&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;Procedural code gets information then makes decisions. Object-oriented code tells objects to do things.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;In order for objects to do things, they may need to ask questions about their own data. Though the first rule of East-oriented Code says that you should return &lt;code&gt;self&lt;/code&gt;, internal private methods don&amp;rsquo;t need to follow this rule. We can and might need to create query methods to allow the object to make decisions.&lt;/p&gt;

&lt;p&gt;It&amp;rsquo;s easy to begin designing an object by specifying what it&amp;rsquo;s attributes are:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Person
  attr_reader :name, :nickname, :gender
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When we do that, we also implicitly allow other objects to use these attributes and make decisions:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if person.nickname =~ /^DJ/
  person.setup_playlist_preferences('house')
else
  person.setup_playlist_preferences('classical')
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the sample code above we&amp;rsquo;re using a method &lt;code&gt;setup_playlist_preferences&lt;/code&gt; which accepts a single argument. The decision about what value to set is made outside of the &lt;code&gt;person&lt;/code&gt; object. As additional options are added to the system, this &lt;code&gt;if&lt;/code&gt; may have &lt;code&gt;elsif&lt;/code&gt; clauses added to it or it may turn into a &lt;code&gt;case&lt;/code&gt; statement. With public attributes, those changes can appear in multiple places in your system, which can lead to headaches when the structures of your objects change.&lt;/p&gt;

&lt;p&gt;Alternatively, we could command the object to do what we want:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;person.setup_playlist_preferences
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Any decision about what to do to setup preferences can be made inside the &lt;code&gt;setup_playlist_preferences&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;Here&amp;rsquo;s a summary from the &lt;a href=&quot;http://c2.com/cgi/wiki?TellDontAsk&quot;&gt;C2 wiki&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;&lt;p&gt;Very very short summary: It is okay to use accessors to get the state of an object, as long as you don&amp;rsquo;t use the result to make decisions outside the object. Any decisions based entirely upon the state of one object should be made &amp;lsquo;inside&amp;rsquo; the object itself.&lt;/p&gt;&lt;/blockquote&gt;

&lt;p&gt;One way to prevent decisions about an object from being made outside that object is to limit the public information:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Person
  private
  attr_reader :name, :nickname, :gender
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you like this, check out the new book I&amp;rsquo;m writing: &lt;a href=&quot;http://clean-ruby.com/dsl&quot;&gt;Ruby DSL Handbook&lt;/a&gt; which is currently half-off the final price. It&amp;rsquo;s designed to be a guide to help you make decisions about how to build your own DSL and compressions of concepts.&lt;/p&gt;</description>
      <pubDate>Tue, 10 Mar 2015 00:00:00 GMT</pubDate>
      <guid>http://www.saturnflyer.com/blog/jim/2015/03/10/the-4-rules-of-east-oriented-code-rule-2/</guid>
      <link>http://www.saturnflyer.com/blog/jim/2015/03/10/the-4-rules-of-east-oriented-code-rule-2/</link>
    </item>
  
    <item>
      <title>The 4 Rules of East-oriented Code: Rule 1</title>
      <dc:creator>Jim Gay</dc:creator>
      <description>&lt;p&gt;4 simple rules are pretty easy to remember, but a bit harder to understand and apply.&lt;/p&gt;

&lt;p&gt;A key concept of East-oriented Code is to enforce the use of commands by returning the object receiving a message.&lt;/p&gt;

&lt;p&gt;Here&amp;rsquo;s a simple example of what that looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def do_something
  # logic for doing something omitted...
  self
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It&amp;rsquo;s incredibly simple to follow.&lt;/p&gt;

&lt;p&gt;Here are the rules I set forth in my presentation at &lt;a href=&quot;http://confreaks.com/videos/4825-RubyConf2014-eastward-ho-a-clear-path-through-ruby-with-oo&quot;&gt;RubyConf&lt;/a&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Always return self&lt;/li&gt;
&lt;li&gt;Objects may query themselves&lt;/li&gt;
&lt;li&gt;Factories are exempt&lt;/li&gt;
&lt;li&gt;Break the rules sparingly&lt;/li&gt;
&lt;/ol&gt;


&lt;p&gt;The first three are hard rules. The fourth, obviously, is more lenient.
We&amp;rsquo;ll get to some guidance on breaking the rules in the future but for now let&amp;rsquo;s look at applying this to your code.&lt;/p&gt;

&lt;h2&gt;Rule 1: Always return self&lt;/h2&gt;

&lt;p&gt;Although this rule is simple at first, it inevitably leads to the queston of getter methods.&lt;/p&gt;

&lt;p&gt;What if your objects had no getters? What if an object&amp;rsquo;s &lt;code&gt;name&lt;/code&gt; attribute simply was inaccessible to an external object?&lt;/p&gt;

&lt;p&gt;You can make your data private by either marking your &lt;code&gt;attr_accessor&lt;/code&gt;s as private:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;attr_accessor :name
private :name
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or you can use the &lt;code&gt;private&lt;/code&gt; method to mark all of the following defined methods to be private:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;private
attr_accessor :name
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;How you choose to do it will depend upon your code, but this would help you remove any getter methods.&lt;/p&gt;

&lt;p&gt;Now this leaves you with a conundrum. How do you use the information?&lt;/p&gt;

&lt;p&gt;If you have a need for that &lt;code&gt;name&lt;/code&gt;, what can you do?&lt;/p&gt;

&lt;p&gt;The only answer is to create a command which will apply the data to the thing you need.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def apply_name_to(form)
  form.name = name
  self
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The restricitions we put in our code are often self-imposed.&lt;/p&gt;

&lt;p&gt;We can make whatever we want, so what&amp;rsquo;s to stop us from putting Rails model data manipulation in it&amp;rsquo;s view template?
Nothing concrete stops us from doing so.&lt;/p&gt;

&lt;p&gt;The same goes for getter methods like &lt;code&gt;name&lt;/code&gt;. If it is publicly accessible by external objects, then we can create whatever &lt;code&gt;if&lt;/code&gt; and &lt;code&gt;case&lt;/code&gt; statements we want. We can put logic wherever we want.&lt;/p&gt;

&lt;p&gt;If we create our own restrictions, we can guide ourselves and other programmers to the direction we intend for our application&amp;rsquo;s structure.&lt;/p&gt;

&lt;h2&gt;Creating restrictions&lt;/h2&gt;

&lt;p&gt;I&amp;rsquo;ve written about the Forwardable library in the past not only because of it&amp;rsquo;s usefulness, but because we can copy the same pattern to create our own DSL.&lt;/p&gt;

&lt;p&gt;Forwardable provides methods which create getter methods for related objects. But what if we created our own DSL for commands to related objects? What if we could pass the messages on, but allow the related object to handle the values?&lt;/p&gt;

&lt;p&gt;Here&amp;rsquo;s what that could look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Person
  command :send_email =&amp;gt; :emailer
end
person = Person.find(1) # get some record
person.emailer = Emailer.get # get some object to handle the emailing
person.send_email
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&amp;rsquo;s a lot of pseudo-code but the parts we care about are sending the command to a related object. Commands return the receiving object, queries will return a value.&lt;/p&gt;

&lt;p&gt;Here&amp;rsquo;s what that code would look like without our (yet unimplemented) &lt;code&gt;command&lt;/code&gt; DSL.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Person
  def send_email
    emailer.send_email
    self
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Any code which uses a &lt;code&gt;Person&lt;/code&gt; will have to rely on the command to do its own thing. This prevents a programmer from leaking logic out of the person.&lt;/p&gt;

&lt;p&gt;What should happen when the email is sent? With the structure above, this code, can&amp;rsquo;t make decisions:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if person.send_email
  # do one thing
else
  # this will never work now
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you find that you often write code like the &lt;code&gt;if&lt;/code&gt; statement above, you might wonder &amp;ldquo;where does that logic go now?&amp;rdquo; Now, you&amp;rsquo;ll be forced to write this code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;person.send_email
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And this means that your &lt;code&gt;send_email&lt;/code&gt; now has the job of handling what to do:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Person
  def send_email
    emailer.send_email
    # do some other things...
    self
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That might provide you with better cohesion; the related behaviors remain together.&lt;/p&gt;

&lt;p&gt;Getting back to that &lt;code&gt;command&lt;/code&gt; DSL we used above&amp;hellip;&lt;/p&gt;

&lt;p&gt;This was the final point of my presentation at RubyConf: you can build guidlines like this for yourself.&lt;/p&gt;

&lt;p&gt;I created a gem called &lt;code&gt;direction&lt;/code&gt; to handle enforcing this East-oriented approach. I&amp;rsquo;ll write more about that later, but it shows that I can create signals to other developers on my team. I can take a simple concept like a command and simplify my code to show other developers what&amp;rsquo;s happening:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Person
  command :send_email =&amp;gt; :emailer
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt; Building a DSL can aid in communication. The language and terminology we use can compress ideas into easily digestible parts.&lt;/p&gt;

&lt;p&gt; If you like this, check out my new book: &lt;a href=&quot;http://clean-ruby.com/dsl&quot;&gt;Ruby DSL Handbook&lt;/a&gt; designed to be a guide to help you build your own compressions of concepts.&lt;/p&gt;</description>
      <pubDate>Tue, 10 Feb 2015 00:00:00 GMT</pubDate>
      <guid>http://www.saturnflyer.com/blog/jim/2015/02/10/the-4-rules-of-east-oriented-code-rule-1/</guid>
      <link>http://www.saturnflyer.com/blog/jim/2015/02/10/the-4-rules-of-east-oriented-code-rule-1/</link>
    </item>
  
    <item>
      <title>Ruby Forwardable deep dive</title>
      <dc:creator>Jim Gay</dc:creator>
      <description>&lt;p&gt;The Forwardable library is one of my favorite tools from Ruby&amp;rsquo;s standard library both for simplifying my own code and learning how to make simple libraries.&lt;/p&gt;

&lt;p&gt;I find that the best way to understand how code works is to first understand why it exists and how you use it. In a previous article I wrote about &lt;a href=&quot;http://www.saturnflyer.com/blog/jim/2014/11/15/shorter-simpler-code-with-forwardable/&quot;&gt;the value of using Forwardable&lt;/a&gt;. It takes code like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def street
  address.street
end

def city
  address.city
end

def state
  address.state
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And makes it as short as this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;delegate [:street, :city, :state] =&amp;gt; :address
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Shrinking our code without losing behavior is a great feature which Forwardable provides. So how does it work?&lt;/p&gt;

&lt;h2&gt;Modules and their context&lt;/h2&gt;

&lt;p&gt;Forwardable is a module, which can be used to add behavior to an object. Most of the of modules I see tend to be used like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Person
  include SuperSpecial
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But Forwardable is different and is designed to be used with the &lt;code&gt;extend&lt;/code&gt; method.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require 'forwardable'
class Person
  extend Forwardable
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Using &lt;code&gt;extend&lt;/code&gt; includes the module into the &lt;code&gt;singleton_class&lt;/code&gt; of the current object. There&amp;rsquo;s a bit more to it than that, but here&amp;rsquo;s a simple model to keep in mind: use &lt;code&gt;include&lt;/code&gt; in your class to add instance methods; use &lt;code&gt;extend&lt;/code&gt; in your class to add &lt;strong&gt;class methods&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Now that we have that out of the way, to use Forwardable, use &lt;code&gt;extend&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;Defining forwarding rules&lt;/h2&gt;

&lt;p&gt;My most often used feature of Forwardable is the one you saw above: &lt;code&gt;delegate&lt;/code&gt;. It accepts a hash where the keys can be symbol or string method names, or an array of symbols and strings. The values provided are accessors for the object to which you&amp;rsquo;ll be forwarding the method names.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Person
  extend Forwardable

  delegate [:message_to_forward, :another_method_name] =&amp;gt; :object_to_receive_message,
            :single_method =&amp;gt; :other_object
end
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Other shortcuts&lt;/h3&gt;

&lt;p&gt;Forwardable provides a few methods, and most commonly you&amp;rsquo;ll see their shortened versions: &lt;code&gt;delegate&lt;/code&gt;, &lt;code&gt;def_delegator&lt;/code&gt;, and &lt;code&gt;def_delegators&lt;/code&gt;. These are actually alias methods of the originals.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;alias delegate instance_delegate
alias def_delegators def_instance_delegators
alias def_delegator def_instance_delegator
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;delegate&lt;/code&gt; method we reviewed above is a bit of a shortcut for similar behavior that other methods provide in Forwardable.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;def_delegators&lt;/code&gt; method accepts multiple arguments but it&amp;rsquo;s sometimes hard for me to remember that one argument in particular is important. The first argument is the reference to the related object, the next arguments are used to create methods to forward.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class SpecialCollection
  extend Forwardable

  def_delegators :@collection, :clear, :first, :push, :shift, :size
  # The above is equivalent to:
  delegate [:clear, :first, :push, :shift, :size] =&amp;gt; :@collection
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, with &lt;code&gt;delegate&lt;/code&gt; there&amp;rsquo;s a visual separation between the accessor and the list of methods.&lt;/p&gt;

&lt;p&gt;There&amp;rsquo;s more of a difference between &lt;code&gt;delegate&lt;/code&gt; and &lt;code&gt;def_delegators&lt;/code&gt; too.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def instance_delegate(hash) # aliased as delegate
  hash.each{ |methods, accessor|
    methods = [methods] unless methods.respond_to?(:each)
    methods.each{ |method|
      def_instance_delegator(accessor, method)
    }
  }
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here the code loops through the hash argument changing the keys into arrays of methods if they aren&amp;rsquo;t already arrays, and then calls the &lt;code&gt;def_instance_delegator&lt;/code&gt; method for each item in the array. Here&amp;rsquo;s what &lt;code&gt;def_instance_delegators&lt;/code&gt; looks like. Note that this is the plural version:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def def_instance_delegators(accessor, *methods) # aliased as def_delegators
  methods.delete(&quot;__send__&quot;)
  methods.delete(&quot;__id__&quot;)
  for method in methods
    def_instance_delegator(accessor, method)
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This method speficially restricts the use of &lt;code&gt;__send__&lt;/code&gt; and &lt;code&gt;__id__&lt;/code&gt; in forwarded messages. These methods are particularly important in communicating with the forwarding object and determining its identity. If you only used &lt;code&gt;delegate&lt;/code&gt; and (for some strange reason) you specify either of &lt;code&gt;__send__&lt;/code&gt; or &lt;code&gt;__id__&lt;/code&gt; then those methods will pass right through. That might do exactly what you want or it might introduce some buggy behavior. This is mostly easy to avoid since you&amp;rsquo;ll likely specify all the methods you need.&lt;/p&gt;

&lt;p&gt;The different behavior is important to know, however, if you want to do a blanket forward for all methods from another class of objects:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class SpecialCollection
  extend Forwardable

  def_delegators :@collection, *Array.instance_methods
  # The above is equivalent to:
  delegate [*Array.instance_methods] =&amp;gt; :@collection
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you do that, you&amp;rsquo;ll likely see warnings from Ruby like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;warning: redefining `__send__' may cause serious problems
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Don&amp;rsquo;t say Ruby didn&amp;rsquo;t warn you!&lt;/p&gt;

&lt;p&gt;But &lt;code&gt;def_delegators&lt;/code&gt; is a plural version of &lt;code&gt;def_delegator&lt;/code&gt; which provides more options than the two we&amp;rsquo;ve been reviewing.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class SpecialCollection
  extend Forwardable

  def_delegator :@collection, :clear, :remove
  def_delegator :@collection, :first
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The method &lt;code&gt;def_delegator&lt;/code&gt; accepts only three arguments. The first is the accessor for the related object (which will receive the forwarded message) and the second is the name of the message to be sent to the related object. The third argument is the name of the method to be created on the current class and is optional; if you don&amp;rsquo;t specify it then the second argument will be used.&lt;/p&gt;

&lt;p&gt;Here&amp;rsquo;s what the above &lt;code&gt;def_delegator&lt;/code&gt; configurations would look like if you wrote out the feature yourself:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class SpecialCollection
  extend Forwardable

  # def_delegator :@collection, :clear, :remove
  def remove
    @collection.clear
  end

  # def_delegator :@collection, :first
  def first
    @collection.first
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can see how the optional third argument is used as the name of the method on your class (e.g. &lt;code&gt;remove&lt;/code&gt; instead of &lt;code&gt;clear&lt;/code&gt;).&lt;/p&gt;

&lt;h2&gt;How the methods are created&lt;/h2&gt;

&lt;p&gt;We looked at how Forwardable adds class methods to your class. Let&amp;rsquo;s look at the most important one:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def def_instance_delegator(accessor, method, ali = method)
  line_no = __LINE__; str = %{
    def #{ali}(*args, &amp;amp;block)
      begin
        #{accessor}.__send__(:#{method}, *args, &amp;amp;block)
      rescue Exception
        $@.delete_if{|s| Forwardable::FILE_REGEXP =~ s} unless Forwardable::debug
        ::Kernel::raise
      end
    end
  }
  # If it's not a class or module, it's an instance
  begin
    module_eval(str, __FILE__, line_no)
  rescue
    instance_eval(str, __FILE__, line_no)
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It looks like a lot, and it is, but let&amp;rsquo;s strip it down to it&amp;rsquo;s simplest form rather than review everything at once. Here&amp;rsquo;s a simpler version:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def def_instance_delegator(accessor, method, ali = method)
  str = %{
    def #{ali}(*args, &amp;amp;block)
      #{accessor}.__send__(:#{method}, *args, &amp;amp;block)
    end
  }
  module_eval(str, __FILE__, __LINE__)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Remembering, of course, that &lt;code&gt;def_instance_delegator&lt;/code&gt; is aliased as &lt;code&gt;def_delegator&lt;/code&gt; we can see that a string is created which represents what the method definition will be and saved to the &lt;code&gt;str&lt;/code&gt; variable. Then then that variable is passed into &lt;code&gt;module_eval&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It&amp;rsquo;s good to know that &lt;code&gt;module_eval&lt;/code&gt; is the same as &lt;code&gt;class_eval&lt;/code&gt; because I know I often see &lt;code&gt;class_eval&lt;/code&gt; but rarely see the other. Regardless, &lt;code&gt;class_eval&lt;/code&gt; is merely an alias for &lt;code&gt;module_eval&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The string for the generated method is used by &lt;code&gt;module_eval&lt;/code&gt; to create the actual instance method. It evaluates the string and turns it into Ruby code.&lt;/p&gt;

&lt;p&gt;Taking this command &lt;code&gt;def_delegator :@collection, :clear, :remove&lt;/code&gt; here&amp;rsquo;s what string will be generated:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;%{
  def remove(*args, &amp;amp;block)
    @collection.__send__(:clear, *args, &amp;amp;block)
  end
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now it&amp;rsquo;s a bit clearer what&amp;rsquo;s going to be created.&lt;/p&gt;

&lt;p&gt;If you&amp;rsquo;re not familiar with &lt;code&gt;__send__&lt;/code&gt;, know that it&amp;rsquo;s also aliased as &lt;code&gt;send&lt;/code&gt;. If you need to use the &lt;code&gt;send&lt;/code&gt; method to match your domain language, you can use it and rely on &lt;code&gt;__send__&lt;/code&gt; for the original behavior. Here, the Forwardable code is cautiously avoiding any clashes with your domain language just in case you do use &amp;ldquo;send&amp;rdquo; as a behavior for some object in your system.&lt;/p&gt;

&lt;p&gt;Maybe you&amp;rsquo;re scratching your head about what either of those methods are at all. &lt;em&gt;What the heck is &lt;code&gt;send&lt;/code&gt; anyway!?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The simplest way to describe it is to show it. This &lt;code&gt;@collection.__send__(:clear, *args, &amp;amp;block)&lt;/code&gt; is equivalent to:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@collection.clear(*args, &amp;amp;block)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All Ruby objects accept messages via the &lt;code&gt;__send__&lt;/code&gt; method. It just so happens that you can use the dot notation to send messages too. For any method in your object, you could pass it&amp;rsquo;s name as a string or symbol to &lt;code&gt;__send__&lt;/code&gt; and it would work the same.&lt;/p&gt;

&lt;p&gt;It&amp;rsquo;s important to note that using &lt;code&gt;__send__&lt;/code&gt; or &lt;code&gt;send&lt;/code&gt; will run private methods as well. If the &lt;code&gt;clear&lt;/code&gt; method on &lt;code&gt;@collection&lt;/code&gt; is marked as private, the use of &lt;code&gt;__send__&lt;/code&gt; will circumvent that.&lt;/p&gt;

&lt;p&gt;The methods defined by Forwardable will accept any arguments as specified by &lt;code&gt;*args&lt;/code&gt;. And each method may optionally accept a block as referred to in &lt;code&gt;&amp;amp;block&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It&amp;rsquo;s likely that the acceptance of any arguments and block will not affect your use of the forwarding method, but it&amp;rsquo;s good to know. If you send more arguments than the receiving method accepts, your forwarding method will happily pass them along and your receiving method will raise an &lt;code&gt;ArgumentError&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;Managing errors&lt;/h2&gt;

&lt;p&gt;Forwardable maintains a regular expression that it uses to strip out references to itself in error messages.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;FILE_REGEXP = %r&quot;#{Regexp.quote(__FILE__)}&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This creates a regular expression where the current file path as specified by &lt;code&gt;__FILE__&lt;/code&gt; is escaped for characters which might interfere with a regular expression.&lt;/p&gt;

&lt;p&gt;That seems a bit useless by itself, but remembering the original implementation of &lt;code&gt;def_instance_delegator&lt;/code&gt; we&amp;rsquo;ll see how it&amp;rsquo;s used:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;str = %{
  def #{ali}(*args, &amp;amp;block)
    begin
      #{accessor}.__send__(:#{method}, *args, &amp;amp;block)
    rescue Exception
      $@.delete_if{|s| Forwardable::FILE_REGEXP =~ s} unless Forwardable::debug
      ::Kernel::raise
    end
  end
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This code recues any exceptions from the forwarded message and removes references to the Forwardable file.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;$@&lt;/code&gt; or &amp;ldquo;dollar-at&amp;rdquo; global variable in Ruby refers to the backtrace for the last exception raised. A backtrace is an array of filenames plus their relevant line numbers and other reference information. Forwardable defines these forwarding methods to remove any lines which mention Forwardable itself. When your receive an error, you&amp;rsquo;ll want the error to point to &lt;strong&gt;your&lt;/strong&gt; code, and not the code from the library which generated it.&lt;/p&gt;

&lt;p&gt;Looking at this implementation we can also see a reference to &lt;code&gt;Forwardable::debug&lt;/code&gt; which when set to a truthy value will &lt;em&gt;not&lt;/em&gt; remove the Forwardable lines from the backtrace. Just use &lt;code&gt;Forwardable.debug = true&lt;/code&gt; if you run into trouble and want to see the full errors. I&amp;rsquo;ve never needed that myself, but at least it&amp;rsquo;s there.&lt;/p&gt;

&lt;p&gt;The next thing to do, of course, is to re-raise the cleaned up backtrace. Again Forwardable will be careful to avoid any overrides you may have defined for a method named &lt;code&gt;raise&lt;/code&gt; and explicitly uses &lt;code&gt;::Kernel::raise&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The double colon preceding &lt;code&gt;Kernel&lt;/code&gt; tells the Ruby interpreter to search from the top-level namespace for &lt;code&gt;Kernel&lt;/code&gt;. That means that if, for some crazy reason, you&amp;rsquo;ve defined a &lt;code&gt;Kernel&lt;/code&gt; underneath some other module name (such as &lt;code&gt;MyApp::Kernel&lt;/code&gt;) then Forwardable will use the standard behavior for &lt;code&gt;raise&lt;/code&gt; as defined in Ruby&amp;rsquo;s &lt;code&gt;Kernel&lt;/code&gt; and not yours. That makes for predictable behavior.&lt;/p&gt;

&lt;h2&gt;Applying the generated methods&lt;/h2&gt;

&lt;p&gt;After creating the strings for the forwarding methods, Forwardable will attempt to use &lt;code&gt;module_eval&lt;/code&gt; to define the methods.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# If it's not a class or module, it's an instance
begin
  module_eval(str, __FILE__, line_no)
rescue
  instance_eval(str, __FILE__, line_no)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If the use of module_eval raises an error, then it will fallback to &lt;code&gt;instance_eval&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;I&amp;rsquo;ve yet to find a place where I&amp;rsquo;ve needed this instance eval feature, but it&amp;rsquo;s good to know about. What this means is that not only can you extend a class or module with Forwardable, but you can extend an individual object with it too.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;object = Object.new
object.extend(Forwardable)
object.def_delegator ...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This code works, depending of course on what you put in your &lt;code&gt;def_delegator&lt;/code&gt; call.&lt;/p&gt;

&lt;h2&gt;Forwarding at the class or module level&lt;/h2&gt;

&lt;p&gt;All these shortcuts for defining methods are great, but they only work for instances of objects.&lt;/p&gt;

&lt;p&gt;Fortunately &lt;code&gt;forwardable.rb&lt;/code&gt; also provides SingleForwardable, specifically designed for use with modules (classes are modules too).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Person
  extend Forwardable
  extend SingleForwardable
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the above sample you can see that &lt;code&gt;Person&lt;/code&gt; is extended with &lt;strong&gt;both&lt;/strong&gt; &lt;code&gt;Forwardable&lt;/code&gt; and &lt;code&gt;SingleForwardable&lt;/code&gt;. This means that this class can use shortcuts for forwarding methods for both instances and the class itself.&lt;/p&gt;

&lt;p&gt;The reason this library defines those longform methods like &lt;code&gt;def_instance_delegator&lt;/code&gt; instead of just &lt;code&gt;def_delegator&lt;/code&gt; is for a scenario like this. If you wanted to use &lt;code&gt;def_delegator&lt;/code&gt; and those methods were not aliased, you&amp;rsquo;d need to choose only one part of this library.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Person
  extend Forwardable
  extend SingleForwardable

  single_delegate [:store_exception] =&amp;gt; :ExceptionTracker
  instance_delegate [:street, :city, :state] =&amp;gt; :address
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can probably guess from the above code, the names of each library&amp;rsquo;s methods matter.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;alias delegate single_delegate
alias def_delegators def_single_delegators
alias def_delegator def_single_delegator
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you use both Forwardable and SingleForwardable, you&amp;rsquo;ll want to avoid the shortened versions like &lt;code&gt;delegate&lt;/code&gt; and be more specific by using &lt;code&gt;instance_delegate&lt;/code&gt; for Forwardable, or &lt;code&gt;single_delegate&lt;/code&gt; for SingleForwardable.&lt;/p&gt;

&lt;p&gt;If you liked this article, please join my mailing list at &lt;a href=&quot;http://clean-ruby.com&quot;&gt;http://clean-ruby.com&lt;/a&gt; or pick up the book today!&lt;/p&gt;

&lt;p&gt;&lt;form action=&quot;http://campaign.saturnflyer.com/t/r/s/fuitlt/&quot; method=&quot;post&quot; id=&quot;subForm&quot; style=&quot;background-color: #F7F1CD; border: 1px solid #999; padding: 1em;&quot;&gt;&lt;/p&gt;

&lt;h3&gt;Clean Up Your Code and get a Free chapter of Clean Ruby&lt;/h3&gt;


&lt;p&gt;If you liked this post and want more like it, get periodic tips in your inbox by leaving your email address below. &lt;img src=&quot;http://solarhost.s3.amazonaws.com/21/assets/58/book-shadow.png&quot; alt=&quot;Clean Ruby&quot; title=&quot;Get a Free sample chapter&quot; style=&quot;border:0 none;&quot; /&gt;&lt;/p&gt;


&lt;p&gt;To get more information about cleaning up your objects, classes, and code, then check out &lt;a href=&quot;http://clean-ruby.com&quot;&gt;Clean Ruby&lt;/a&gt;, an ebook which will describe ways to &lt;a href=&quot;http://www.clean-ruby.com/&quot;&gt;keep your code clean, maintainable, and focused on business value&lt;/a&gt;. Make your OOP more obvious, easier to understand, easier to test, and easier to maintain.&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;fuitlt-fuitlt&quot;&gt;Email: (required)&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-fuitlt-fuitlt&quot; id=&quot;fuitlt-fuitlt&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-name&quot; id=&quot;name&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;clear: both;&quot;&gt;
  &lt;input type=&quot;submit&quot; value=&quot;Subscribe for Ruby tips and a Free chapter!&quot; /&gt;&lt;/p&gt;


&lt;p&gt;&lt;/form&gt;&lt;/p&gt;</description>
      <pubDate>Tue, 20 Jan 2015 00:00:00 GMT</pubDate>
      <guid>http://www.saturnflyer.com/blog/jim/2015/01/20/ruby-forwardable-deep-dive/</guid>
      <link>http://www.saturnflyer.com/blog/jim/2015/01/20/ruby-forwardable-deep-dive/</link>
    </item>
  
    <item>
      <title>Avoiding clever mistakes when displaying data with missing values</title>
      <dc:creator>Jim Gay</dc:creator>
      <description>&lt;p&gt;In a previous article I showed a snippet of code I’ve used for displaying address information. There were some tricks to getting it right that are valuable to know when you have to handle missing data.&lt;/p&gt;

&lt;p&gt;Here’s the problem, and how to solve it.&lt;/p&gt;

&lt;p&gt;Let’s setup some simple data to use:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;street = &quot;123 Main St.&quot;
city = &quot;Arlington&quot;
province = &quot;VA&quot;
postal_code = &quot;222222&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The original implementation of displaying an address looked like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;&quot;.tap do |string|
  string &amp;lt;&amp;lt; street unless street.nil?
  string &amp;lt;&amp;lt; city unless city.nil?
  string &amp;lt;&amp;lt; province unless province.nil?
  string &amp;lt;&amp;lt; postal_code unless postal_code.nil?
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;While that code will skip missing data if there is any, it will just mash all the bits together creating this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;123 Main St.ArlingtonVA22222&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That’s not particularly helpful for displaying a readable address. I’m looking for it to display like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;123 Main St.
Arlington, VA 22222&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here’s what I tried next:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[street, [city, [province, postal_code].join(' ')].join(', ')].join(&quot;\n&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Thinking I was very clever, I ran the code with complete data and it worked quite well.&lt;/p&gt;

&lt;p&gt;When I ran it with incomplete data I found that it didn’t work the way I expected. For example, if the city value was nil, I got this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;123 Main St.
, VA 22222&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That leading comma is just visual noise, so we need to remove that. Realizing that I had nil values in my arrays, I knew I could reach for the compact method to strip them out. After compacting the array, the join wouldn’t have nil values to address; they’d be gone.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[street, [city, [province, postal_code].compact.join(' ')].compact.join(', ')].compact.join(&quot;\n&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This worked perfectly, to remove the leading comma:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;123 Main St.
VA 22222&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Just to be sure I got it right, I began checking other data. Next, with the city set to “Arlington” and this time with the province and postal_code set to nil I saw this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;123 Main St.
Arlington, &quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Ugh! Now I had a trailing comma. Why wasn’t this working!? Using compact should remove the nil values.&lt;/p&gt;

&lt;p&gt;The problem was that I had an empty array for the province and postal_code. That meant that with both values removed from the array using compact, this was happening:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[].join(' ') #=&amp;gt; &quot;&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And because that empty array returned a value of an empty string, I was joining the city value with an empty string. In this case, compact was doing nothing for me.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[city, [province, postal_code].compact.join(' ')].compact.join(', ')
# is the same as:

[city, &quot;&quot;].compact.join(', ')]
# which yields:

&quot;Arlington, &quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So there it was. Finally I found my problem that what I thought was nil, wasn’t.&lt;/p&gt;

&lt;p&gt;I decided to change the values to nil if they were empty strings:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;province_and_postal_code = [province, postal_code].compact.join(' ')
province_and_postal_code = nil if province_and_postal_code.empty?

city_province_postal_code = [city, province_and_postal_code].compact.join(', ')
city_province_postal_code = nil if city_province_postal_code.empty?

[street, city_province_postal_code].compact.join(&quot;\n&quot;)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Finally, I got the output I needed:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&quot;123 Main St.
Arlington&quot;

&quot;123 Main St.
VA 22222&quot;

&quot;123 Main St.
Arlington, VA 22222&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;My clever one-liner gave me unexpected behavior. While it was nice and short, it was also wrong. Eventually I ended up with code which is not just correct, but much more readable too. You might have your own preferences for how to handle these nil values. What would you do differently?&lt;/p&gt;

&lt;p&gt;&lt;form action=&quot;http://campaign.saturnflyer.com/t/r/s/fuitlt/&quot; method=&quot;post&quot; id=&quot;subForm&quot; style=&quot;background-color: #F7F1CD; border: 1px solid #999; padding: 1em;&quot;&gt;&lt;/p&gt;

&lt;h3&gt;Clean Up Your Code and get a Free chapter of Clean Ruby&lt;/h3&gt;


&lt;p&gt;If you liked this post and want more like it, get periodic tips in your inbox by leaving your email address below. &lt;img src=&quot;http://solarhost.s3.amazonaws.com/21/assets/58/book-shadow.png&quot; alt=&quot;Clean Ruby&quot; title=&quot;Get a Free sample chapter&quot; style=&quot;border:0 none;&quot; /&gt;&lt;/p&gt;


&lt;p&gt;To get more information about cleaning up your objects, classes, and code, then check out &lt;a href=&quot;http://clean-ruby.com&quot;&gt;Clean Ruby&lt;/a&gt;, an ebook which will describe ways to &lt;a href=&quot;http://www.clean-ruby.com/&quot;&gt;keep your code clean, maintainable, and focused on business value&lt;/a&gt;. Make your OOP more obvious, easier to understand, easier to test, and easier to maintain.&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;fuitlt-fuitlt&quot;&gt;Email: (required)&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-fuitlt-fuitlt&quot; id=&quot;fuitlt-fuitlt&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;width: 45%; float: left;&quot;&gt;
  &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;&lt;br /&gt;&lt;input type=&quot;text&quot; name=&quot;cm-name&quot; id=&quot;name&quot; /&gt;&lt;/p&gt;


&lt;p style=&quot;clear: both;&quot;&gt;
  &lt;input type=&quot;submit&quot; value=&quot;Subscribe for Ruby tips and a Free chapter!&quot; /&gt;&lt;/p&gt;


&lt;p&gt;&lt;/form&gt;&lt;/p&gt;</description>
      <pubDate>Tue, 30 Dec 2014 00:00:00 GMT</pubDate>
      <guid>http://www.saturnflyer.com/blog/jim/2014/12/30/avoiding-clever-mistakes-when-displaying-data-with-missing-values/</guid>
      <link>http://www.saturnflyer.com/blog/jim/2014/12/30/avoiding-clever-mistakes-when-displaying-data-with-missing-values/</link>
    </item>
  
  
</channel>
</rss>
