Remove Assignments to Parameters(移除对参数的赋值)

  1. int discount(int inputVal, int quantity, int yearToDate){
  2. if(inputVal > 50) inputVal -=2;
  3. }

修改后:

  1. int discount(int inputVal, int quantity, int yearToDate){
  2. int result = inputVal;
  3. if(inputVal > 50) result -=2;
  4. }

做法

  • 建立一个临时变量,吧待处理的参数值赋予它

  • 以”对参数的赋值”为界,将其后所有对此参数的引用点,全部替换为”对此临时变量的引用”

  • 修改赋值语句,使其改为对新建之临时变量赋值

  • 编译,测试

    如果代码的语义是按引用传递的,请在调用端检查调用后是否还使用了这个参数。也要检查有多少个按引用传递的参数被赋值后又被使用。请尽量只以return方式返回一个值。如果需要返回的值不止一个,看看可否把需返回的大堆数据变成单一对象,或干脆为每个返回值设计对应的一个独立函数

范例

  1. int discount(int inputVal ,int quantity, int yearToDate){
  2. if(inputVal > 50)inputVal -= 2;
  3. if(quantity > 100)inputVal -= 1;
  4. if(yearToDate > 10000)inputVal -= 4;
  5. return inputVal;
  6. }

修改后:

  1. int discount(int inputVal ,int quantity, int yearToDate){
  2. int result = inputVal;
  3. if(inputVal > 50)result -= 2;
  4. if(quantity > 100)result -= 1;
  5. if(yearToDate > 10000)result -= 4;
  6. return result;
  7. }