Search code examples
language-agnosticcoding-style

Is it bad practice to use temporary variables to avoid typing?


I sometimes use temporary variables to shorten the identifiers:

private function doSomething() {
    $db = $this->currentDatabase;
    $db->callMethod1();
    $db->callMethod2();
    $db->callMethod3();
    $db->...
}

Although this is a PHP example, I'm asking in general:

Is this bad practice? Are there any drawbacks?


Solution

  • This example is perfectly fine, since you are using it in functions/methods.

    The variable will be unset right after the method/function ends - so there's not much of a memory leak or what.

    Also by doing this, you "sort of" implemented DRY - don't repeat yourself.

    Why write so many $this->currentDatabase when you can write $db. And what if you have to change $this->currentDatabase to some other values?