为什么要使用变量名"temp"?认为是不好的做法吗? [英] Why using a variable name "temp" considered a bad practice?

查看:377
本文介绍了为什么要使用变量名"temp"?认为是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我从专业程序员那里提出要审查的代码时,他们往往会指出使用名为temp的变量是不好的",但似乎没人知道为什么.

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.

为什么认为它不好?

推荐答案

temp确实并不意味着有用.一个更好的问题是:是否必须?

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

在不知道上下文(代码中如何使用上下文)的情况下,很难说出它的作用以及temp是否是一个好名字. 如果您经常或不在本地使用变量,则该名称必须具有描述性.如果使用temp之类的名称(例如,在相邻的三行中使用三次)就可以了.

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;
}

此函数应该立即执行(根据其名称)实际上应执行的操作(根据其结构).在这种情况下,我强烈建议首选短名称(并自动使用非描述性名称).我什至会说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 ;)

但是:

  • 如果经常使用该变量,那么它显然很重要,并且应有"一个更好的名字.
  • 如果在函数中相距较远的位置(非本地)使用相同的变量,则当您给它赋予可识别的名称时,它可以帮助程序员记住"含义.

这篇关于为什么要使用变量名"temp"?认为是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆