Day at the Office: Using vi’s Macros

I had a method which was too long.  It was a switch/case statement, with a bunch of processing at each case label.    There were a lot of local variables that were being used:

var foo=something; 
var bar=yetsomethingelse; 
var scooby=another thing; 
var fred=yetanotherthing; 

switch(thingy) { 
  case A: 
    stuff with foo and bar; 
    break; 
    
  case B: 
    stuff with foo and scooby; 
    break; 
    
  case C:
    stuff with foo, bar, and scooby; 
    break;
    
  case D:
    stuff with foo, bar, and fred; 
    break;
    
  default:
    throw new exception(); 
    break;
}

In this mockup I only have 4 variables; the real one had 12.   And each case label was probably 20-30 lines of code.

Apply Refactoring: Replace Local Variables with a Class

And the name of the class shall be context. 

So I had a lot of errors, where this:

if (something(fred)) anotherthing(barney)

had to become this:

if (something(c.Fred) anotherthing(c.Barney);

The Vi Macro

The exact keystrokes were:

  Begin with cursor on fred
qn Begin Recording a Macro to register n.  I use n because its on the right hand, and the @ symbol to apply a macro is on the left hand.
~ Change case (now we have Fred)
h Go left one (because ~ moves you forward)
i Enter insert mode
c. <Esc> type in “c.” and exit insert mode
l move the cursor right one.
q Finish recording

 

Then, I hit rebuild (F6), looked at the list of errors, and then primed myself:

/fred @n  / enter  (find fred, fix fred macro, find next fred)

@n / enter   (fix fred, find next fred)

Apply Refactoring: Extract Methods

Now that I had a reasonable list of variables (one mega-variable, the “context”, and some other minor ones), I could take the meat of each case block and extract out a method for just that case block.

The result: cleaner code… and in one case, I could pass my context variable one layer deeper and extract out some other meaningful stuff from it (which I had not pulled out into a variable before).

Author: sunnywiz

Me.

Leave a Reply

Your email address will not be published. Required fields are marked *