范例(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;
}
以臨時變量取代對參數(shù)的賦值動作,得到下列代碼:
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
}
還可以為參數(shù)加上關(guān)鍵詞final,從而強制它遵循[不對參數(shù)賦值]這一慣例:
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
}
不過我的承認(rèn),我并不經(jīng)常使用final來修飾參數(shù),因為我發(fā)現(xiàn),對于提高短函數(shù)的清晰度,這個辦法并無太大幫助。我通常會在較長的函數(shù)中使用它,讓它幫助我檢查參數(shù)是否被做了修改。
我從下列這段簡單代碼開始:
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;
}
以臨時變量取代對參數(shù)的賦值動作,得到下列代碼:
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
}
還可以為參數(shù)加上關(guān)鍵詞final,從而強制它遵循[不對參數(shù)賦值]這一慣例:
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
}
不過我的承認(rèn),我并不經(jīng)常使用final來修飾參數(shù),因為我發(fā)現(xiàn),對于提高短函數(shù)的清晰度,這個辦法并無太大幫助。我通常會在較長的函數(shù)中使用它,讓它幫助我檢查參數(shù)是否被做了修改。