Code Refactoring

Published in category Programming
on Christian Mayer's Weblog.

What’s the main challenge when refactoring or adding new features to a software project? You need to know what the dependencies are doing. You need to know what the code you change is doing. At least to know, roughly, which part does what. To avoid side-effects.

When I’m going to change code I first make an overview of all parts that are affected. I’m creating a mental map of the call tree. Maybe degugging each single step to the affected locations. This process takes more or less time, depending on whether I wrote the original code or not.

Refactoring using PHPStorm 2017.1

After using PHPStorm for about two weeks for a professional project I admit it’s helpful. (You may want to read PHP: detect undefined variables.) My problem with PHPStorm is that it has too many features. It’s too bloated.

There are some traps where I rather consider using the command-line instead of PHPStorm.

Consider this code:

<?php

class Foo{
    public function getName(){return 'bla';}
}

class Bar{
    private $foo;
    public function setFoo($foo){
        $this->foo = $foo;
    }
    public function getFoo(){
        return $this->foo;
    }
}

$foo = new Foo();
$bar = new Bar();

$foo->setBar($foo);
$foo->getBar()->getName();

?>

Let’s assume you want to rename getName() and you don’t use annotations. Maybe you use annotations but missing on some locations in your code. If you use PHPStorm and rename getName(), the last line, $foo->getBar()->getName();, will be missed renamed. If you rely on PHPStorm it’s possible you miss something. You cannot be 100% sure that all functions, classes, etc. have annotations and get catched by PHPStorm.

Even if you add the correct @return annotation to function getFoo() and @var annotation to the private Bar variable $foo, PHPStorm will miss it.

Not to miss the caller line, $foo->getBar()->getName();, it’s better to split this statement and use an annotation for it:

/** @var Foo $bar2 */
$bar2 = $foo->getBar();
$bar2->getName();

It’s also a good approach to consult the command-line when refactoring code. Use grep -R to search for a certain string within a directory tree. I personally prefer ack over grep. But grep is pre-installed on every Linux and UNIX operating system.

Recent Posts

About the Author

Christian is a professional software developer living in Vienna, Austria. He loves coffee and is strongly addicted to music. In his spare time he writes open source software. He is known for developing automatic data processing systems for Debian Linux.