EugeneP
EugeneP

Reputation: 12003

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 should be a better practice?

Upvotes: 1

Views: 194

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500515

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.

Upvotes: 13

Bill the Lizard
Bill the Lizard

Reputation: 405765

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.

Upvotes: 1

MHarris
MHarris

Reputation: 1821

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.

Upvotes: 1

Related Questions