Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 788
Daniel Rikowski Avatar asked Nov 18 '09 11:11

Daniel Rikowski


2 Answers

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?

like image 101
mauris Avatar answered Sep 21 '22 07:09

mauris


Actually, you're not trying to avoid typing (otherwise, you'd use a completion mechanism in your editor), but you're just making your function more readable (by using "abbreviations") which is a good thing.

Drawbacks will show up when you start doing this to avoid typing (and sacrifice readability)

like image 34
Gyom Avatar answered Sep 20 '22 07:09

Gyom