Tag Archives: building the bridge

Building a Bridge a.k.a Parallel Changes

Several days ago, we had a coding dojo at Digital Natives: we wanted to reimplement a method without changing its purpose. To do this, we used a technique called building a bridge, which is also known as parallel change. The technique itself is quite simple, and in this post I’m going to show you how to use it and why.

For example, I have this piece of code, which is presumably part of a larger code base:

class Foo
  # ...
  def count(first, last)
    counter = 0
    first.upto(last) do |i|
      counter += 1 if prime?(i)
    end
    counter
  end
 
  private
  def prime?(value)
    [2,3,5,7,11,13,17,19].include?(value)
  end
 
  # ...
end

Maybe it is not working very well – its limitation is obvious -, but it is more than enough for now. Let’s say that we decide to change the prime? method. The same method, the same purpose, only the algorithm will be different. So we create a new method called prime_next? and implement that method either with TDD or in a regular fashion. After it is done, we’ll have something like this:

class Foo
  # ...
  private
  def prime?(value)
    [2,3,5,7,11,13,17,19].include?(value)
  end
 
  public
  def prime_next?(value)
    # a fancy algorithm probably based on Fermat's primality test
  end
  # ...
end

When our tests or gut feelings indicate that the new method is complete, we replace the method names, so prime? will be come prime_next? and prime_next? will become prime? (hint: it is easier and safer to switch the actual method names than to change the references. For example, in ruby we don’t have a fancy IDE with the “rename method...” functionality so it would take some time until all the references are changed, not mentioning the expressions evaluated at runtime).

We run some more tests – or trust our feelings – so that we see whether the new algorithm is working with the rest of the code base. If everything is up and running, we clean up and deliver:

class Foo
  # ...
  def count(first, last)
    counter = 0
    first.upto(last) do |i|
      counter += 1 if prime?(i)
    end
    counter
  end
 
  private
  def prime?(value)
    # a fancy algorithm probably based on Fermat's primality test
  end
  # ...
end

This was the “how”, but it seems a lot of unnecessary work for a change, doesn’t it? It may seem like that at first, but I prefer to do it, because it ensures that while I’m working on my changes, I can still work with the rest of the team, and that the code I’m working on is well tested. Now, let’s see the “why”.

Read more »

VN:F [1.9.17_1161]
Rating: 0.0/10 (0 votes cast)