Byzantine Reality

Searching for Byzantine failures in the world around us

Improving Your Code

Last time we looked at how Ruby makes using shell commands way easier than the Java approach. However, there was a little problem with it: it didn’t always work. As a side note, we also can make it smaller, which is what we’ll take care of today. Improving your code is an important part of coding: code isn’t static!

With that in mind, let’s look at the problem. Traceroute spits out output like this:

traceroute to www.amazon.com (72.21.210.11), 1 hops max, 40 byte packets
 
1  192.168.1.1 (192.168.1.1)  1.395 ms  0.876 ms  0.818 ms

Our old solution worked fine since the gateway (192.168.1.1) is the same in two places on that second line. But on other networks, the first 192.168.1.1 will be replaced by the domain name of the server with that IP. So now we aim to fix this and make our code smaller at the same time. First, the fix:

result = `traceroute -m 1 www.amazon.com`
if result =~ /\((\d*.\d*.\d*.\d*)\)/
  puts
"The gateway is #$1"
end

This accomplishes that just fine. However, since we all love to play the game of golf, let’s make it a little bit smaller. We know we’ll always get the IP back in the right spot, so let’s forgo any error checking or the like. That leaves us with:

result = `traceroute -m 1 www.amazon.com`
puts
"The gateway is #{result.match(/\((\d*.\d*.\d*.\d*)\)/)}"

Not bad! Naturally we can play golf all day and make this code completely unreadable, but that’s not the point here. Our code is now nice and concise, still readable, and we’ve shown two different ways to do regex in Ruby. Let’s look at the final score:

     lines   words chars
     
14      50     502 ExecTest.java
       
6      21     141 ExecRubyOld.rb
       
2      11     105 ExecRubyNew.rb

Don’t get too hung up on the score though. We didn’t try to optimize the Java code and lines/words/chars aren’t the greatest measurement scheme (as mentioned earlier). But it’s fun to pretend like it is sometimes.