读书人

Reduce Scope of Variable - 缩小变量

发布时间: 2013-03-21 10:08:17 作者: rapoo

Reduce Scope of Variable -- 缩小变量作用域

Reduce Scope of Variable

Refactoring contributed by Mats Henricson

You have a local variable declared in a scope that is larger than where it is used

你有一个局部变量,其声明和使用离得太远。

Reduce the scope of the variable so that it is only visible in the scope where it is used

缩小变量的作用域使得它只在被使用的作用域内可见。

void foo(){    int i = 7;    // i is not used here    if (someCondition)    {        // i is used only within this block    }    // i is not used here}

Reduce Scope of Variable - 缩小变量作用域

void foo(){    // i can not be used here    if (someCondition)    {        int i = 7;        // i is used only within this block    }    // i can not be used here}

Motivation

There are several problems with local variables declared in too large scopes. One is that the variable may be declared but never used, as is the case if someConditionin the above example is false. Since declarations of variables in many cases costs computational cycles, you may end up wasting time for nothing. Another problems is that it clutters the name space. If you have several objects of the same type within the same scope, naming them can be quite contrieved - (user1, user2, user3 or firstUser, otherUser, nextUser). You may also end up having one variable hiding another variable with the same name in a larger scope, something most seasoned programmers can testify is very confusing and error prone.

局部变量作用域太大会有一些问题。其一,声明了但从未使用,譬如上面的例子中someCondition为false。变量声明在很多情况下花费时钟周期,你可以结束这种没有价值的浪费。其二,会使变量名变得杂乱。如果你有三五个相同类型的对象在相同作用域内,你可能这么命名他们user1, user2, user3 or firstUser, otherUser, nextUser,显得不太自然。你可以修改他们,因为如果不修改掉,容易产生混淆和错误。

Mechanics

读书人网 >其他相关

热点推荐