这样的风格好吗?
我的函数中有一些参数接收和传递相同的值。我应该将所有参数变量命名为相同吗?
示例:
// assume numMonth = 12
// assume numYear = 2000
int promptMonth(); // returns numMonth
int promptYear(); // returns numYear
int daysInMonth(int numMonth, int numYear); // numMonth and numYear will always
int daysInYear(int numYear); // be sent to these.
bool isLeapYear(int numYear); // daysInYear() and daysInMonth() call
// this function and send it numYear
// (which would be 2000 in this case).
由于将相同的值传递给每个参数,所有这些参数是否应该命名相同?
I have some parameters in my functions that receive and pass around the same value. Should I name all the parameter variables the same?
Example:
// assume numMonth = 12
// assume numYear = 2000
int promptMonth(); // returns numMonth
int promptYear(); // returns numYear
int daysInMonth(int numMonth, int numYear); // numMonth and numYear will always
int daysInYear(int numYear); // be sent to these.
bool isLeapYear(int numYear); // daysInYear() and daysInMonth() call
// this function and send it numYear
// (which would be 2000 in this case).
Should all those parameters be named the same since the same value is passed to each of them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
同样,我假设您指的是函数参数名称
numYear
。是的,以有意义的方式命名变量始终是一个好习惯,该方式表明所传递值的含义/目的。
这些变量是不同函数的一部分,因此范围仅限于这些函数,因此如果您考虑到这一点,就不存在多个定义的问题。
By same, I assume you mean the function parameter name
numYear
.Yes it is always good practice to name the variables in a meaningful way which indicates the meaning/purpose of the value being passed.
And those variables are part of different functions, hence there scope is limited to those functions only, So there is no problem of multiple definitions if you are thinking of that.
一般来说,这种风格是个好主意。你绝对应该遵循它,但仍然存在误用和误解的空间。
让我解释一下自己
int
适合作为年份值。对于更复杂的情况,您应该考虑为输入变量使用特殊类型。
例如,考虑将一些整数更改为:
您是否发现现在不仅不必使用复杂的变量名称,而且还可以进行特殊的打印和检查?
可以输出
Generally this style is a good idea. You should definitely follow it, but there is still space for misuse and misinterpretation.
Let me explain myself
int
is suitable as a year value.For more complex cases you should consider using a special type for your input variables.
For example, consider changing some of your integers into:
Can you see that now not only you don't have to use complex variable names, but you are also able to do special prints and checks?
could output