Archive for the ‘Study’ Category

Show Intent with Better Naming

March 8, 2011

I had an interesting experience at a code retreat with the creator, Corey Haines. I created some code that I felt was really perfect. I didn’t think there was room for much improvement, but it only took Corey a few seconds in passing to find a flaw. It starts with this list of rules for simple design:

  1. Passes tests – the code should be test-driven, and the tests should all pass.
  2. No duplication – often known as DRY – don’t repeat yourself. Every distinct piece of information in the system should have one (and only one) representation in the code.
  3. Expresses intent – the code should be self-explanatory.
  4. Small – methods, classes, indeed the entire application shouldn’t be any bigger than absolutely necessary.

My Original Version

I won’t explain what this code is supposed to do. That might defeat the point. See if you can figure out which principal I violated with this code. I’ll say it’s not Rule #1, but showing the tests would take up too much room.

def new_status current_status, neighbor_count
  return :alive if neighbor_count == 3
  return current_status if neighbor_count == 2
 
  :dead
end

The Problem

Corey asked me one question: what if one of the requirements changes? And there it was. In an attempt to do the most in the fewest lines, I’d over-refactored the method. Not only had I made the method brittle if business requirements should change in the future, I’d factored out the intent of the method itself.

As usual, one good software practice begets another. Test-driven development results in smaller, simpler methods for instance. And in this case, showing intent in your code reduces brittleness. So how do you accomplish this?

The Solution

Express the problem domain in the code itself. Here’s my example, reworked:

def new_status current_status, neighbor_count
  return :dead if overpopulated?(neighbor_count)
      || underpopulated?(neighbor_count)

  return :alive if population_perfect?(neighbor_count)
 
  current_status
end
 
def overpopulated? neighbor_count
  neighbor_count > 3
end
 
def underpopulated? neighbor_count
  neighbor_count < 2
end
 
def population_perfect? neighbor_count
  neighbor_count == 3
end

This code is longer, but it shows intent much more clearly. You don’t even need to know what “overpopulated” is to understand what the method is doing. But if you want to know, or need to change it, it’s easy. In fact, we’re passing neighbor_count around a lot, so it looks like it’s time to abstract this into a class:

class Cell
  def initialize current_status, neighbor_count
    @current_status = current_status
    @neighbor_count = neighbor_count
  end
 
  def next_status
    return :dead if overpopulated? || underpopulated?
    return :alive if population_perfect?
 
    @current_status
  end
 
  private
 
  def overpopulated?
    @neighbor_count > 3  
  end
 
  def underpopulated?
    @neighbor_count < 2
  end
 
  def population_perfect?
    @neighbor_count == 3
  end
end

Now the code is much more readable, and understandable. We’re now clearly showing intent. And now, just for fun, the tests:

class CellTest << Test::Unit::TestCase
  def test_should_die_when_alive_and_overpopulated
    cell = Cell.new :alive, 4
    assert_equal :dead, cell.next_status
  end
 
  def test_should_die_when_alive_and_underpopulated
    cell = Cell.new :alive, 1
    assert_equal :dead, cell.next_status
  end
 
  def test_should_live_when_alive_and_perfect_population
    cell = Cell.new :alive, 3
    assert_equal :alive, cell.next_status
  end
 
  def test_should_stay_alive_by_default_when_alive
    cell = Cell.new :alive, 2
    assert_equal :alive, cell.next_status
  end
 
  def test_should_die_when_dead_and_overpopulated
    cell = Cell.new :dead, 4
    assert_equal :dead, cell.next_status
  end
 
  def test_should_die_when_dead_and_underpopulated
    cell = Cell.new :dead, 1
    assert_equal :dead, cell.next_status
  end
 
  def test_should_live_when_dead_and_perfect_population
    cell = Cell.new :dead, 3
    assert_equal :alive, cell.next_status
  end
 
  def test_should_stay_dead_by_default
    cell = Cell.new :dead, 2
    assert_equal :dead, cell.next_status
  end
end

Code Retreat in Boulder, Colorado

February 26, 2011

I’m in beautiful downtown Boulder, getting ready to attend a code retreat with Ruby greats like Corey Haines, Chad Fowler, Dave Thomas*, Mike Clark, Michael Feathers and many more.

Last night I hung out with some KC friends and we setup our dev environments for the event. I got motivated, and created a base environment on GitHub you can download. It runs your tests automatically using Watchr every time you save your code file, and if you’re on a mac it even takes a screen shot at each save! Now you can go back and relive the magic. Maybe string them together into a video with a little commentary, and boom – easy post-retreat blog video.

Use the link above, and let me kno w if it was useful!

*not the Wendy’s guy, as my wife likes to ask. You’d think since the world is down to just one living, notable Dave Thomas that joke would get a little old. I think the people who grew up watching Wendy’s commercials will also have to die out first :)

Ruby’s Splat Operator

December 22, 2010

Ruby is a dynamic language. One of the things it lets you do is define methods with an unknown (or variable) number of arguments. It does this using the splat operator. But the splat operator can actually be used for other things in your code, especially if you’re using Ruby 1.9. That’s because a small change to how splat operators work make them much more useful.

In the beginning

The humble splat operator was first used to slurp up unnamed arguments to a method:

def sum *numbers
  numbers.inject{|sum, number| sum += number}
end

Sometimes, this is just syntactic sugar, because passing a list of numbers like this:

sum(1, 2, 3)

Is more intuitive and prettier, and less error-prone, than passing them as an explicit array:

sum([1, 2, 3])

In many cases though, the splat operator is more than just a pretty face. Take Ruby’s own method_missing instance method, that is available in every class. If defined, it will attempt to handle any calls to methods that don’t explicitly exist:

class Person
  def method_missing sym, *args
    if sym.to_s =~ /^(\w+)=$/
      instance_variable_set "@#{$1}", args[0]
    else
      instance_variable_get "@#{sym}"
    end
  end
end

method_missing must be able to accept an unknown number of arguments, since just about any method call could be thrown at it. In this case, we’re using it to get and set instance variables without having to define them first using attr_accessor:

ruby-1.8.7-p299 > p = Person.new
 => #<Person:0x10018f640 @turtles=nil> 
ruby-1.8.7-p299 > p.turtles = 'I like them'
 => "I like them" 
ruby-1.8.7-p299 > p.turtles
 => "I like them" 
ruby-1.8.7-p299 > p.squirrels
 => nil 
ruby-1.8.7-p299 > p.squirrels = 'are okay'
 => "are okay" 
ruby-1.8.7-p299 > p.squirrels
 => "are okay" 

We’ve just created a class that lets us define any attributes we want, and our method doesn’t care whether *args contains zero arguments, or a hundred.

It gets unintentionally cooler

Up through Ruby 1.8 you could use this splat operator, in a limited fashion, for things other than method argument lists. You could use it to flatten an array, in contexts where it was the last element in the list:

ruby-1.8.7-p299 > last_numbers = [3, 4, 5]
 => [3, 4, 5] 
ruby-1.8.7-p299 > all_numbers = [1, 2, *last_numbers]
 => [1, 2, 3, 4, 5]

The splat operator took the last_numbers array and expanded it inline! Now our new array contains five numbers, instead of two numbers and a nested array. This comes in handy for meta-programming. So let’s try putting the splat operator somewhere else in the array:

ruby-1.8.7-p299 > middle_numbers = [2, 3, 4]
 => [2, 3, 4] 
ruby-1.8.7-p299 > all_numbers = [1, *middle_numbers, 5]
SyntaxError: compile error
(irb):4: syntax error, unexpected ',', expecting ']'
all_numbers = [1, *middle_numbers, 5]
                                  ^
	from (irb):4
ruby-1.8.7-p299 > first_numbers = [1, 2, 3]
 => [1, 2, 3] 
ruby-1.8.7-p299 > all_numbers = [*first_numbers, 4, 5]
SyntaxError: compile error
(irb):6: syntax error, unexpected ',', expecting ']'
all_numbers = [*first_numbers, 4, 5]
                              ^
	from (irb):6

We can’t use the splat operator anywhere else except the end of a list, just like in method calls. This really limits its value in Ruby 1.8.

Things get intentionally cooler

As of Ruby 1.9, however, the splat operator has been given a little more love, and now it can be used almost anywhere. Basically, any array that is given the splat operator will “flatten” itself, and return the list of elements NOT in an array. Now we can do cool stuff like this:

ruby-1.9.2-p0 > first_numbers = [1, 2, 3]
 => [1, 2, 3] 
ruby-1.9.2-p0 > middle_numbers = [4, 5, 6]
 => [4, 5, 6] 
ruby-1.9.2-p0 > last_numbers = [7, 8, 9]
 => [7, 8, 9] 
ruby-1.9.2-p0 > all_numbers = [*first_numbers, *middle_numbers, *last_numbers]
 => [1, 2, 3, 4, 5, 6, 7, 8, 9] 

This is handy for all sorts of meta-programming challenges – namely, handling dynamic argument lists. It’s also great when you’re building an array out of smaller pieces where some of the pieces are scalars (single values) and some are arrays. Let’s say we have a Family class, that contains myself, my parents, and my siblings. I want a method that returns everybody in one large array. The usage would look like this:

ruby-1.9.2-p0 > family = Family.new
 => #<Family:0x000001018ed2d8> 
ruby-1.9.2-p0 > family.myself = 'Greg'
 => "Greg" 
ruby-1.9.2-p0 > family.parents = ['Mike', 'Carol']
 => ["Mike", "Carol"] 
ruby-1.9.2-p0 > family.siblings = ['Peter', 'Bobby', 'Marsha', 'Jan', 'Cindy']
 => ["Peter", "Bobby", "Marsha", "Jan", "Cindy"] 
ruby-1.9.2-p0 > family.everybody
 => ["Greg", "Mike", "Carol", "Peter", "Bobby", "Marsha", "Jan", "Cindy"] 

If I want to do this without the splat operator (as I’d have to in Ruby 1.8) it would look like this:

class Family
  attr_accessor :myself, :parents, :siblings
  
  def everybody
    members = []
    members << myself
    members += parents
    members += siblings
  end
end

As you can see, I have to go line-by-line, interacting with the members array differently depending on if I’m adding one value or an array. Here’s how you’d do it without the splat operator:

class Family
  attr_accessor :myself, :parents, :siblings
  
  def everybody
    [myself, *parents, *siblings]
  end
end

Much cleaner! This version is shorter and easier to understand. This is a technique that might not seem useful, until you have a need for it. Then you’ll start finding uses for it everywhere.

Review of the “Database is Your Friend” Workshop by Xavier Shay

August 23, 2010

Xavier ShayThis Saturday I had the privilege of attending Xavier Shay’s “Database is Your Friend” workshop right here in Kansas City. It explores the enterprise domain of high-traffic, mission-critical databases in Rails. At $350, the price tag trumps just about every regional Ruby or Rails conference I’ve heard of. It was worth the price, and more. It would have been well worth the expense of travel and lodging if it had been out of town.

I’ve never had such a thorough learning experience. Xavier had a git repository setup with several branches of a basic Rails app, which we all cloned. He would give a 10-15 minute overview of a difficult concept, then we would checkout a given branch, and spend about 20 minutes completing whatever part of the code Xavier had omitted. We used test-driven development much of the time, which forced us to fully understand the cause and effect of each technique.

Xavier was in constant motion, visiting each of the six students to ensure everybody got it. After all, the exercises themselves were mission critical, because the following lessons built upon them. After experiencing this, I wonder why all teaching isn’t done this way. The “Long Lecture, Here’s Your Homework, Now Get Out” system I remember from college could benefit a lot from this.

It’s obvious a lot of love went into the design of the workshop. The flow was so natural that several times, one of us would ask a question and Xavier would answer that the next segment addresses it. The result was a natural progression of solving more and more complex problems.

If you struggle with (or wonder about) data integrity and high-traffic database issues, take the opportunity to learn from Xavier Shay on his current tour.

PS –

While this workshop is definitely worth travelling, I didn’t have to. Wes Garrison of Databasically, who helps organize our monthly Ruby meetings, took the initiative. Xavier normally attaches his workshop to conferences, but Wes looked at the schedule and saw that Xavier had a small gap between his Chicago and Austin dates. Wes offered to arrange both travel and lodging for Xavier, who luckily agreed to squeeze another workshop into his busy schedule. Wes, thank you.

Introducing: Rails Kata

June 24, 2010

A Scary Idea is Born

In a previous post about RailsConf and Code Kata, I decided to take action, and begin publicly practicing my programming craft. Without further ado, I give you my brainchild: I’ve designed my first personal kata.

I’ve been meaning to get into the Cucumber testing framework for a long time, so my first kata was to create an entire MVC stack, test driven, using Cucumber and Shoulda. I recorded it. It took 100 minutes. So I went back to the drawing board for something more fundamental – basic data modeling with my chosen testing framework and editing tools. Voila, a ten minute kata practicing the most fundamental rails tools.

I’m posting my work on Vimeo, due to their unlimited video lengths. I invite you to record your own version of this kata, and post the video link in the comments! Let’s learn from each other.

So here’s my first try. I’m not good at screencasting just yet. I also have a sore throat, making my narration a little scratchy. But I welcome feedback.

My RailsConf Takeaway – Kata and Code Retreats

June 16, 2010

I attended RailsConf last week, and it was amazing. I met a lot of amazing people (including a handful of personal geek heroes) and became truly fired up about my personal craft of programming. Serendipity played a big part, as a series of events lined up to help me form my new strategy for being a better developer.

On the plane ride out, I read the first half of Malcolm Gladwell’s Outliers. Chapter 2 had me spellbound. The title: The 10,000 Hour Rule. In study after study, the author showed that to truly master a craft, only a nominal amount of intelligence and “natural” talent are required. For instance, any IQ above 120 should be more than capable. After that basic filter, what separates the masters from the rest is *practice*. About 10,000 hours, by most studies’ estimates. That could be practicing baseball, music (not just performing, but practicing to intentionally get better), or chess. You get the idea.

Fast forward to the Ignite RailsConf event Sunday night, where 14 speakers had 5 minutes each to give a lightning presentation, with no overtime. Three of those speakers mentioned the 10,000 hour rule. Later in the week, Yehuda Katz gave a keynote where he said he’d only been programming since 2004! Just six years, about half my professional career, and he’d mastered Ruby and Rails to the level of being a core member of the Rails team. How? Finding “impossible” challenges, and doing them. This is, of course, the essence of practice – making a concerted effort to complete tasks that were previously out of your ability.

But it gets better. BohConf (the official unconf of RailsConf) hosted a mini code retreat Tuesday afternoon. Code retreats, as defined by Corey Haines, blend Dave Thomas’ concept of Code Kata with pair programming and repetition. You pair with someone, and work to solve a common programming problem, most typically Conway’s Game of Life. You have about 30 minutes to write a purely test-driven solution. Then you reflect on what you were able to get done, delete the code, find a new coding partner, and start all over! This is practice and feedback combined!

Over the week, the idea rolled around my head. And during my extended 12-hour plane trip home. And all weekend. I need to be practicing, in order to master my craft. I need to create my own collection of code kata – “fundamentals” I can practice over and over until they become second nature. I also want to pair program more, and perform my kata in public where I can be open to feedback.

I have a plan for this, which I’ve already put in motion. Stay tuned :)

UPDATE: I have posted my first (official) kata at vimeo. Read my blog post about it.

Kansas City Ruby User Group’s January Meeting

January 17, 2010

Last Tuesday, the Kansas City Ruby User Group (KCRUG) had its monthly meeting. There were 15-20 of us in attendence, with Nate Bunnyfield checking in from the Lawrence on Rails group in nearby Lawrence, Kansas. I’ve been meaning to go to one of their meetings, which are every other Thursday.

Shashank Date gave the main presentation, about Ruby blocks, procs, and lambdas. His presentation is here:

Ryan Smith also presented his Decorator pattern for Rails:

We don’t have our video setup exactly as we’d like it yet, but we’re getting there. Thanks to the presenters, along with Wes Garrison who recorded and processed the video!

Announcement: Kansas City Ruby User Group Meeting

January 11, 2010

Every month, the Kansas City Ruby User group meets to discuss current events in the development world, and learn from each other. This month, Shashank Date will be offering a refresher of his talk from last year on Procs and lambdas. Often, Ruby on Rails developers can be strong on Rails, and light on Ruby.

This talk covers one of the most powerful Ruby features that is used all the time by the Rails framework itself. Newer developers, however, may not realize just how easy it is to harness the power of blocks, and by extension Proc and lambda calls, in methods. I might also stand up and give a brief rundown on binding, a closely related concept.

The Where and When

If you live in the Kansas City area, join us Tuesday January 11, 2010 at 6:30pm here:

Centriq Foss
8700 State Line Road
Leawood, KS 66206

Visit the meetup page for more info.

Preview

To give some background, here’s a code snippet that illustrates a block:

def do_for_each(array=[], &amp;block)
   array.each{|element| block.call element}
 end

do_for_each([1,2,3]){|x| puts x}

A Ruby block is a chunk of code that can be passed to a method and run at will. This code prints each element of the array on its own line. If this looks familiar, that’s because it’s really a lamer version of the Array class’ map instance method.

When you pass a block to a method like this, you’re recreating a Proc object implicitly. You don’t have to do anything extra, and Ruby knows what to do with this extra code hanging off the method call. But what if, for instance, you needed to pass *two* blocks into a method? Here’s one way:

def custom_print(words, quiet, loud)
  words.each do |word|
    if word =~ /!$/
      puts loud.call(word)
    else
      puts quiet.call(word)
    end
  end
end

words = ['hello', 'world!', 'turkey']
custom_print(words, lambda{|w| w + '.'}, lambda{|w| w.upcase})

In this example, words are “loud” if they end in an exclamation point. I chose to end quiet words with a period, and to capitalize loud words. Please join us Tuesday for a much more detailed explanation.

Programming Erlang

March 23, 2009

Some of my Kansas City Ruby friends have started a buzz about Erlang. I’m a die-hard rubyist, but for the first time in my life I can see that I was a die-hard C/C++ programmer before Perl (tried to write CGI apps in C!), and I was a die-hard Perl hacker before Ruby. And it’s not a matter of abandoning Ruby at all – it’s more a matter of adding another shelf in my developer’s toolbox, so I really can pick the best tool for each job.

What I’m doing about it

I recently bought the e-book Programming Erlang by Joe Armstrong. It’s from the good people at Pragmatic Programmers. I’m viewing Erlang with a skeptical eye at the moment, so I got a book I know I can trust. If the Pragmatic Programmers can’t get me to fall in love with Erlang, I’m probably not capable of loving it. Also, it’s under $23 to download!

What I like so far

I’m two chapters into the book, and I believe (although just peripherally) that Erlang can solve a lot of concurrency issues. This has great potential due to multi-core, multi-processor machines. It also transcends one single machine, and allows easier networking of many machines to do whatever it is you need multiple machines for.

What concerns me

So far, reading this book has raised more questions than answers. That’s to be expected – the first couple chapters give you the elevator pitch for Erlang, and jump into some code samples to begin teaching the language. So the amazing benefits won’t be visible for a while. Knowing/hoping that these concerns and questions will likely be answered as I learn Erlang, here they are.

Concerns

  • The code doesn’t seem as elegant as Ruby. I see examples like {_,{_,{_,Name},_},_} = Person. to do what person.name would do in Ruby, and I cringe. To me, this looks like a workaround for not having objects. One that could become very cumbersome.
  • Variables can only be assigned once. This is supposed to ease the mechanics of an inherently multi-threaded language, and maybe it does. And maybe the coding style you use for Erlang makes this trivial.

Questions

  • Does the code end up being readable to others, or yourself in 3 months?
  • Does it solve one problem (concurrency), only to sacrifice good things like OOP?
  • Is there a testing framework so I can keep doing TDD/BDD? I haven’t seen mention of it yet if there is.

Again, I know Erlang is not just a different language, but a different programming concept entirely from Ruby. So I’m going to give it every chance, and keep posting what I learn.

Retro-reading RailsSpace, part 3: Migration Magic

March 15, 2009

This is Part 3 in my series Retro-reading RailsSpace. Despite the book being slightly out of date, and geared toward beginners, it’s a classic. I’m reading it (finally) and posting what I learn.

First, I’m Cheating

I didn’t actually learn today’s migration mojo from RailsSpace directly. The book was more of an inspiration. I saw the old-school t.column call, and for the first time I wondered, “how does it work?”

The “What”

When I started using Ruby on Rails, this was just magic. And I didn’t question it…

create_table :posts do |t|
  t.column  :name, :string  # poof, a string column #
  t.string  :desc           # poof, a string column with even shorter syntax #
  t.integer :views          # poof, an integer column #
end

The “How”

So how does it work? The answer is the TableDefinition class we’ve been using. Don’t see it? It’s the t in t.column, t.string, and t.integer above. When we call create_table an instance of the TableDefinition class is created, and passed to the block (everything between do and end).

column is an instance method of TableDefinition, and adds the column definition to the TableDefinition class. t.string, t.integer, and others just call t.column on the backend.

The “Why”

I think it’s obvious why it was coded this way. Can you imagine a shorter, sweeter syntax? I experimented with lots of SQL shortcuts back in my Perl days, but nothing that worked this well. Blocks in general are a very cool aspect of Ruby, and Rails would lose a lot of its power without them.


Follow

Get every new post delivered to your Inbox.