Why using a variable name “temp” considered a bad practice?

前端 未结 2 2118
抹茶落季
抹茶落季 2021-02-14 22:31

Whenever i put up a code for review from professional programmers they tend to point out that \"using a variable named temp is bad\" but no one seems to know why.

Why is

相关标签:
2条回答
  • 2021-02-14 22:57

    temp indeed doesn't mean anything useful. A better question is: does it have to?

    Without knowing the context (how is it used in your code?), it's hard to say what it's for, and whether temp is a good name. If you use a variable often or non-locally, the name must be descriptive. A name like temp can be fine if you use it, say, three times in three adjacent lines.

    void swapIntPointers(int *a, int *b) {
        int temp = *a;
        *a = *b;
        *b = temp;
    }
    

    It's immediately obvious what this function should do (from its name) and what it actually does (from its structure). In this specific case, I strongly prefer short (and automatically nondescript) names. I'd even say that temp may be a little too long here ;)

    However:

    • If you use the variable often, it's apparently important, and 'deserves' a better name.
    • If you use the same variable in places in the function that are far apart (non-local), it helps programmers to 'remember' the meaning when you give it a recognizable name.
    0 讨论(0)
  • 2021-02-14 23:13

    It's because temp suggests something about the longevity of the variable (temporary) but nothing about the meaning or significance of its content. Variables are generally best named to reflect what their underlying value is intended to represent.

    0 讨论(0)
提交回复
热议问题