【问题标题】:Is this good style?这是好风格吗?
【发布时间】:2011-10-25 06:59:12
【问题描述】:

我的函数中有一些参数接收和传递相同的值。我应该将所有参数变量命名相同吗?

例子:

// 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).

是否应该将所有这些参数命名为相同,因为将相同的值传递给每个参数?

【问题讨论】:

  • “相同值”是什么意思?
  • 我的意思是如果numMonthpromptMonth() 中被赋值为12,那么函数daysInMonth() 中的参数变量numMonth 也是12,因为来自promptMonth()numMonth 被传递给daysInMonth() .所以变量numMonth 是并且应该总是相同的值,在这种情况下是12。

标签: c++ coding-style parameter-passing


【解决方案1】:

同样,我假设您的意思是函数参数名称numYear

是的,以有意义的方式命名变量始终是一种好习惯,这表明所传递值的含义/目的。

这些变量是不同函数的一部分,因此范围仅限于这些函数,所以如果你考虑这个,就不存在多重定义的问题。

【讨论】:

    【解决方案2】:

    一般来说,这种风格是个好主意。您绝对应该遵循它,但仍有误用和误解的空间。

    让我解释一下自己

    • 误解:即使您确实一致地命名变量,读者也可能不会相信您是认真的。
    • 误用:也许没有int 适合作为年份值。

    对于更复杂的情况,您应该考虑为输入变量使用特殊类型。 例如,考虑将您的一些 整数 更改为:

    Month promptMonth();
    Year promptYear();
    
    int daysInMonth( Month m, Year y); 
    int daysInYear( Year y );
    
    bool isLeapYear( Year );
    

    您是否看到现在不仅不必使用复杂的变量名,而且还可以进行特殊的打印和检查?

    cout << "the current month is " << promptMonth();  
    

    可以输出

    the current month is 'October'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-25
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多