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, making 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值