Denis Kulagin
Denis Kulagin

Reputation: 8917

Java: is it ok to use curly brackets to make code more readable?

I was trying to simplify some complex code block and found it useful to separate logical blocks with curly brackets:

{
  // step 1

  {

    // step 2

      {

      // step 3

      }
    }
}

Is it ok to do so it a production code? Extracting those to separate functions is not considered an option, because it requires passing many parameters to them and developing sensible function names - not worth it.

Upvotes: 2

Views: 847

Answers (2)

kamituel
kamituel

Reputation: 35960

Technically - yes, it wouldn't break anything (other than scoping variables, which would be detected at compile time though).

From the code quality point of view - it doesn't sound like something you want to do. If your method is that large, you should really try to break it down into smaller pieces. Maybe the variables you use in that method, if there is so many of them, should be members of the class? Then you would be able to split the method more easily.

The reasons you should avoid having this big, monolithic code blocks, are multiple. It might be harder to reason about such a large method, it'll be probably much harder to unit test it, same for debugging.

As a sidenote, personally, I almost never find myself in a situation when I need to have a function larger than 20-30~ lines of code. If that happens, I start thinking about breaking it down, or maybe even doing some more involved refactoring. One good idea, when thinking about how to break things up, is to write couple of unit tests. If tests turn out to not be well defined, and they tend to have multiple distinct assertions in them etc., it's a sign function is too broad.

Upvotes: 7

KJaeg
KJaeg

Reputation: 686

I think it will lead to the opposite effect. The brackets will hurt the readability, and they will confuse the reader, because he will expect something which really needs to be put between those brackets. I would recommend to use comments like //----------- logical part for abc ------ for that.

It will be more clear using comments than brackets. You can even describe what is happening there.

EDIT says: It is always worth it to seperate huge methods into smaller. Just set them private. A guideline for software quality says: Every method should have just one job.

Upvotes: 2

Related Questions