Playing with Legacy Code - Get seniors buy-in

I was working in a telecommunications company which ships physical VoIP gateway to customers. The code base was already decades old and gained a lot of rust over the years.

Most developers heard of callback hell... But I have seen "if hell":

if ($cond1) {
  if ($cond2) {
    if ($cond3) {
      if ($cond4) {
        //............ continues until there are no screen spaces left


// Well then, start over here
if ($lets_start_over_here) {
  if ($cond1) {
      // ... Over a hundred lines
  }

}

     } else {
     }
    }
  }
}

I believe this was an outcome of our development method. We needed to SSH into the gateway and use VIM to write PHP. Then we tested directly on the gateway. There were no Jenkins, no coding standards nor formatting tools whatsoever. And I believed no one knows about PHPStorm...

One day I realized my time is better spent on dissecting logic instead of playing endless bracket matching game.

The first step is to eliminate all mis-indented code. Thus the following conversation:

Dialogues

Me: Let's run a formatter over the codebase, I can't stand anymore.

Senior: The formatter would cause a large diff. What if the formatter malfunctioned and misplaced something?

Me: ...

How I convinced my senior and saved everyone hours

The trick is to use a code minifier.

  1. Run original code though a minifier -> Get output A
  2. Run original code though a formatter -> Then run though the minifier -> Get output B
  3. If Output A and Output B are the same, we are highly confident the formatter is doing fine.
  4. (If still not convinced, run different minifier to prove it)

Thus I prettier-ed every JS and php-cs-fixer-ed every PHP file. To give senior developers a further sense of safety, I committed the changes in small batches.

Lessons

  • Coding standard must be enforced from the start
  • Use up-to-date development tools (Hey there is PHPStorm)
  • Prepare to convince seniors when you do refactoring