zoukankan      html  css  js  c++  java
  • 重构之重新组织函数(Split Temporary Variable)

    动机:临时变量有各种不同用途,其中某些用途会很自然的导致临时变量被多次赋值。“循环变量”和“结果收集变量”就是典型的例子:循环变量会随循环的每次运行而改变;   结果收集变量负责将“通过这个函数的运算”而构成的某个值收集起来。

             除了这2种情况,还有很多临时变量保存一段冗长代码的运算结果,以便稍后使用。这种临时变量应该只被赋值一次。如果它们被赋值超过一次,就意味着它们在函数中承担了一个以上的职责。如果临时变量承担多个责任,它就应该被替换为多个临时变量,每个变量只承担一个责任。同一个临时变量承担2件不同的事情,会令代码阅读者糊涂。

    1、在待分解临时变量的声明及其第一次被赋值处,修改其名称。如果是结果收集变量就不要分解它。

     2、将新的临时变量声明为const。

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

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

     5、编译、测试。

     6、逐次重复上述过程。每次都在声明处对临时变量改名,并修改下次赋值之前的引用点。

    public class SplitTemporaryVariable {
    
        private double _width,_higth;
    
        public void doGeometoryCal(){
    
            double temp = (_higth +_width)*2;
            System.out.println("The perimeter of this is " + temp);
    
            temp = _higth * _width;
            System.out.println("The area of this is " + temp);
    
    
        }
    
        public void doGeometoryCalAdvanced(){
            double perimeter = (_higth +_width)*2;
            System.out.println("The perimeter of this is " + perimeter);
    
            double area = _higth * _width;
            System.out.println("The area of this is " + area);
        }
    
    }
  • 相关阅读:
    Ubuntu 12.04 国内更新源列表 LINUX软件 偶偶贝塔のBlog
    乱码
    charset
    乱码
    使用 Python 进行线程编程
    Pyphantomjs makes python crash
    乱码
    PyQt v4 Python Bindings for Qt v4 | Документация
    Automated Discovery of Blog Feeds and Twitter, Facebook, LinkedIn Accounts Connected to Business Website « Data Big Bang Blog
    jeanphix/Ghost.py · GitHub
  • 原文地址:https://www.cnblogs.com/newbee0101/p/11970582.html
Copyright © 2011-2022 走看看