开发者

Where shall variables be defined within a method?

Suppose, I have a method with a parameter of Object type. The method returns nothing - void.

First it checks whether the parameter is not null (or any other check, like objectParam.isEnabled())

if (objectParam.isEnabled()) {
    // ok
}

Now, if the condition is satisfied, I need local variables. If it's not, then I don't need any variables.

WHERE SHOULD I define them? Inside the "if scope" or just after the method header?

Of course, I can do it wherever I like, but which way sh开发者_高级运维ould be a better practice?


I believe it's best practice to declare a variable as late as you can, in the most tightly nested scope that you can, ideally at the point where it's initialized with a useful value.

That makes it clearer where and how it's going to be used - when you're looking at the code where it's used, you won't have to look up very far to see the declaration.

In this particular case I disagree with the official Java Style Guide - and so does Josh Bloch. From Effective Java, 2nd edition, item 45:

The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used.

So if you don't need the variable until you've executed a few other statements, don't declare it until that point.


If they're only used within the

if (...) { }

block then they should be declared at the top of that block.

The Java Style Guide has more details.


You should initialize them inside the narrowest scope where they are used, so inside the if block in this case.

void foo(Object obj){
    if (obj != null) {
        int a = 0;
        ...
    } 
}

If they aren't going to be used anywhere outside this block, there's no need to clutter up the method and confuse readers of your code with extra variables declared outside their required scope.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜