diumenge, 16 de febrer del 2014

Naming vars temp

Do not ever create a var called temp ... unless you have a very good reason (you know the consultant answer, "it always depends").

The name temp doesn't give any information at all about what it is contained in a variable. Ok, I went too far, it gives some information: durability of the variable, but still, nothing about what it will contain.

As the durability of a variable is something that comes implicitly with its scope, why don't we leave that responsibility to the scope? Otherwise, we just risk ourselves of being inconsistent (for example, creating  a local variable called global or vice-versa).

As a typical example we´ll have the case of swapping values between variables:

Dirty:
Nicer:
Thanks to renaming all variables and parameters to have self-defining names, readability of the function has been improved (even though the function was so simple it wasn't really required). Anyway, rule sill applies to code of higher complexity, not to say in cases with several "temp" variables (seen them: temp1, temp2, ...).

Cap comentari:

Publica un comentari a l'entrada