zoukankan      html  css  js  c++  java
  • 步步为营 .NET 代码重构学习笔记 三、临时变量(Temporary Variable)

    Split Temporary Variable(剖解临时变量)

    概述

    程序中有某个临时变量被赋值超过一次,它既不是循环变量,也不是一个集用临时变量(collecting temporary variable)

    动机(Motivation)

    临 时变量有各种不同用途,其中某些用途会很自然地导至临时变量被多次赋值.(循环变量)和(集用临时变量)就是两个典型例子:循环变量(loop variable)会随循环的每次运行而改变(例如 for(int i=0;i<10;i++))语句中的i);集用临时变量(collecting temporary variable)负责将(通过整个函数的运算)而构成的某个值收集起来.

    作法(Mechanics)

    1、在(待剖解)之临时变量的声明式及其第一次被赋值处,修改其名称。

    如果稍后之赋值语句是i=j的某表达式形式,就意味着这是个集用临时变量,那么就不要剖解它。集用临时变量的作用通常是累加、字符串接合、写入stream或者向群集(collection)添加元素。

    2、以该临时变量之第二次赋值动作为界,修改此前对该临时变量的所有引用点让它们引用新的临时变量。

    3、在第二次赋值处,重新声明原先那个临时变量。

    示例

    1 public void GetArea(double _height, double _width)
    2 {
    3     double temp = 2 * (_height + _width);
    4     Console.WriteLine(temp);
    5     temp = _width * _height;
    6     Console.WriteLine(temp);
    7 }

    改为:

    1 public void GetArea(double _height, double _width)
    2 {
    3     double temp = 2 * (_height + _width);
    4     Console.WriteLine(temp);
    5     double area = _width * _height;
    6     Console.WriteLine(area);
    7 }

    Remove Assignments to Parameters

    概述

    代码对一个参数进行赋值动作。

    动机(Motivation)

    首选,我们要确定大家都清楚(对参数赋值)这个说法的意思。如果你把一个名为foo的对象作为参数传给某个函数,那么(对参数赋值)意味改变foo,

    使它引用另一个对象。

    作法(Mechanics)

    1、建立一个临时变量,把待处理的参数值赋予它。

    2、以(对参数的赋值动作为界,将其后所有对此参数的引用点,全部替换为(对此临时变量的引用动作)。

    3、修改赋值语名,使其改为对新建之临时变量赋值。
    示例

    1 public int Discount(int inputVal, int quantity, int yeaarToDate)
    2 {
    3     if (inputVal > 50) inputVal -= 2;
    4     if (quantity > 100) inputVal -= 1;
    5     if (yeaarToDate > 10000) inputVal -= 4;
    6     return inputVal;
    7 }

    改为:

    1 public int Discount(int inputVal, int quantity, int yeaarToDate)
    2 {
    3     int result = inputVal;
    4     if (inputVal > 50) result -= 2;
    5     if (quantity > 100) result -= 1;
    6     if (yeaarToDate > 10000) result -= 4;
    7     return result;
    8 }

    总结

    尽量不要对参数进行操作,以一个临时变量取代它。

  • 相关阅读:
    在千万级的数据库查询中,如何提高效率?
    SQL的触发器和存储过程详解
    如何提高mysql的安全性?
    mysql的触发器
    HDU5564 Clarke and digits
    JOI2014Final 飞天鼠
    Topcoder10073 SRM418 BarracksEasy
    Topcoder9902 SRM416 DancingCouples
    Topcoder8307 SRM390 SetOfPatterns
    POJ1741 Tree(点分治)
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/2050712.html
Copyright © 2011-2022 走看看