2011-10-25 41 views
1

我有一些參數在我的函數中接收並傳遞相同的值。我應該將所有參數變量命名爲相同嗎?這是不錯的風格嗎?

例子:

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

如果因爲相同的值傳遞給他們每個人的所有這些參數命名一樣嗎?

+0

你所說的 「同值」 呢? –

+0

我的意思是''numMonth''在'promptMonth()'中被賦值爲12,函數'daysInMonth()'中的參數變量'numMonth'也是12,因爲'promptMonth()'中的'numMonth'被傳遞給'daysInMonth() '。所以變量numMonth和_should_總是相同的值,在這種情況下是12。 –

回答

6

同樣,我假設你的意思是功能參數名稱numYear

是的,以有意義的方式命名變量並指示傳遞值的含義/目的總是一種很好的做法。

而這些變量是不同功能的一部分,因此它的範圍僅限於這些功能,所以如果你正在考慮這個問題,就沒有多重定義的問題。

4

通常這種風格是一個好主意。你一定要遵循它,但仍有誤用和曲解的空間。

讓我解釋一下我自己

  • 誤讀:即使你名稱一致的變量,讀者可能不相信,你是認真的。
  • 濫用:也許沒有任何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'