范例(Examples)
我從下列這段簡單代碼開始:
int discount(int inputVal, int quantity, int yearToDate) {
if(inputVal > 50) inputVal -= 2;
if(quantity > 100) inputVal -= 1;
if(yearToDate > 1000) inputVal -= 4;
return inputVal;
}
以臨時變量取代對參數的賦值動作,得到下列代碼:
int discount(int inputVal, int quantity, int yearToDate) {
int result = inputVal;
if(inputVal > 50) result -= 2;
if(quantity > 100) result -= 1;
if(yearToDate > 1000) result -= 4;
return result
}
還可以為參數加上關鍵詞final,從而強制它遵循[不對參數賦值]這一慣例:
int discount(final int inputVal, final int quantity, final int yearToDate) {
int result = inputVal;
if(inputVal > 50) result -= 2;
if(quantity > 100) result -= 1;
if(yearToDate > 1000) result -= 4;
return result
}
不過我的承認,我并不經常使用final來修飾參數,因為我發現,對于提高短函數的清晰度,這個辦法并無太大幫助。我通常會在較長的函數中使用它,讓它幫助我檢查參數是否被做了修改。
我從下列這段簡單代碼開始:
int discount(int inputVal, int quantity, int yearToDate) {
if(inputVal > 50) inputVal -= 2;
if(quantity > 100) inputVal -= 1;
if(yearToDate > 1000) inputVal -= 4;
return inputVal;
}
以臨時變量取代對參數的賦值動作,得到下列代碼:
int discount(int inputVal, int quantity, int yearToDate) {
int result = inputVal;
if(inputVal > 50) result -= 2;
if(quantity > 100) result -= 1;
if(yearToDate > 1000) result -= 4;
return result
}
還可以為參數加上關鍵詞final,從而強制它遵循[不對參數賦值]這一慣例:
int discount(final int inputVal, final int quantity, final int yearToDate) {
int result = inputVal;
if(inputVal > 50) result -= 2;
if(quantity > 100) result -= 1;
if(yearToDate > 1000) result -= 4;
return result
}
不過我的承認,我并不經常使用final來修飾參數,因為我發現,對于提高短函數的清晰度,這個辦法并無太大幫助。我通常會在較長的函數中使用它,讓它幫助我檢查參數是否被做了修改。