January 29, 2014

Think twice, name it once

There are many best practices for improving your code readability. One of them is to use proper names for classes, methods, objects,... For everything.

Let's check the code below. Can you quickly guess what it does?

class Robot
  def fix_position
    @x = min_x if x < min_x
    @x = max_x if x > max_x
    @y = min_y if y < min_y
    @y = max_y if y > max_y
  end
end

According to method's name it "fixes some position". But let's check the same code again, just with the better method name.

class Robot
  def keep_robot_in_arena
    @x = min_x if x < min_x
    @x = max_x if x > max_x
    @y = min_y if y < min_y
    @y = max_y if y > max_y
  end
end

It is still the same code as before. But now you can instantly say what it does. It keeps your robot in an arena.

You may not understand how it does it from at first glance. But at least you don't have to guess what it does in the first place. And it is much better than something like this.

class Robot
  # keep robot in the arena
  def fix_position
    ...
  end
end

So next time when you are going to use the first name which just came to your mind think again. Other people who will read your code may appreciate it.

Hey there!

My name is Patrik Bóna and I am the only programmer at Memberful. This blog is kind of dead, but I just started my own Ruby on Rails screencast. Follow me on Twitter if you want to be notified about my newest videos.