当前位置:编程学习 > 网站相关 >>

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
}
 
 
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
Move the declaration of the variable to the scope where that variable is used, 易做图 sure that you haven't reduced the scope of the variable too much, so that it isn't in scope at some other place where it is used
 将声明的变量移动到它所被使用的作用域中,但是不要移动的范围太大,造成一些被使用的地方不在变量作用域之内。
Compile and test
编译测试
Additional Comments
When I'm writing new code I find I don't scope my temps any less than method scope. This is because I keep my methods short, so reducing scope any further doesn't add much value. The value of this refactoring is in breaking up a large method. Doing this refactoring can help you see where a variable is used. As such it's a good move before doing Extract Method.
实际上在利用此重构手段之前,最好利用ExtractMethod重构手段将大的方法,重构为一些小的方法。这样能够使你理解变量都干了些什么。所以作者发现很难在一个方法中缩小变量的作用域,因为大的方法已经被重构为一些小的方法。
Also, don't forget you can do this on a field that's only used by one method.
Martin Fowler
补充:综合编程 , 其他综合 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,