Balaji Reddy
Balaji Reddy

Reputation: 5700

Clarification on separate sections of code inside one method with curly brackets

Is that good practice to write code inside one method with separate sections of curly brackets?

    public String getName()
    {
       String returnValue;

          {
             int a=0;
           --- 1 - 5 lines----
          }

          {
            int a=0;
           --- 6 -  10 lines----
          }

    return returnValue;

    }

If it is a good practice, then here is my next question. I’m declaring same variable twice in the method but inside the blocks. Does it mean each block occupies separate\extra memory? Am I right here? Please correct me if I’m wrong.

Upvotes: 0

Views: 99

Answers (4)

Jan Zyka
Jan Zyka

Reputation: 17888

If you feel you need such separate block you should probably consider making such block separate method.

I agree with all who stated it's a bad practice generaly.

Upvotes: 1

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

All the variables are accessible only within the block they are defined, e.g.

{
    int a=0;
    --- 1 - 5 lines----
}

The a variable will be accessible within this block only.

  • Does it occupy much more memory ?

    It's like defining a variable within a loop, for example. You shouldn't worry about it, since memory management is almost passed to the Garbage collector.

  • Is it a good practice ?

    Sometimes such approach can lead to Code smells. Personally, I would prefer skipping such constructions and think of names that make sense. It's good for the source readablity, imho.

Upvotes: 2

Jean Logeart
Jean Logeart

Reputation: 53829

It is usually not a best practice because it makes the code less readable.

As for memory, each block has its own scope and therefore occupies separate memory. More specifically, after having executing the first block, every variable whose scope was limited to the scope of the block can be garbage collected.

Upvotes: 1

Narendra Pathai
Narendra Pathai

Reputation: 41945

It is not a good practice to do that.

When you need to do this then it is a sign of a desperately needed refactor, aka a "code smell" as Martin Fowler puts it.

The scope of the variable is limited to that block and will be garbage collected when the block exits.

{
   int i = 0;
}
//the scope of i will end here and will be eligible for garbage collection

Upvotes: 1

Related Questions