How to Extract an Intention-Revealing Name Using Vim

Joe Ferris

This method has a magic number:

def wait_time
  @env[QUEUE_WAIT_HEADER].to_i / 1000

Let’s extract that to an intention-revealing name. We’ll type:

/1000<Enter>                   # Find the number we want to extract
cwmilliseconds_per_second<Esc> # Replace the number with a variable name
O<Ctrl+A> = <Esc>p             # Assign the replaced number to the variable

The result:

def wait_time
  milliseconds_per_second = 1000
  @env[QUEUE_WAIT_HEADER].to_i / milliseconds_per_second

Under the covers:

  • <Ctrl+A> inserts the last text you typed in insert mode, so the variable name is available after replacing the number
  • Replacing or deleting text in Vim will place that text in your default buffer, so the number is available to put at the end

Assuming your cursor is at the value you want to extract, this creates an intention revealing name in 10 keystrokes, plus the keystrokes it takes to type out the name.

Can you beat my Vim golf?