balancing : Java Glossary

Balancing parentheses() and braces{} is one of the most frustrating tasks in Java coding. Here are some tips to make the job easier.

Part of the problem is Java syntax overuses } for too
many purposes: end of if, end of loop, end of method, end of class … The
compiler will often report a balancing problem far away from where the true error
is. The compiler almost never points you to where the actual problem is. Focus
instead on the code you have most recently changed.

Compile frequently. Then you know where the error must be — in the small
piece of code you most recently changed. Some IDEs (Integrated Development Environments)
maintain a local revision history. Looking through what has changed since the
last time the program was in balance will help you narrow down the problem.

Use an IDE with automated help such as
IntelliJ Idea. It will detect an
imbalance. It will also highlight the match for any delimiter. Some
IDEs
will even insert the missing delimiter for you in the most probable place.

When you cut/copy/paste, move chunks that are balanced. I think
IDEs
should by default refuse to copy/cut/paste unbalanced chunks. When you select, the
selection should automatically expand to make the selection balanced.

Use a code beautifier. The
indentations will help point our where the problem is.

Whenever you key a (, immediately key the matching
), then fill in the payload in between. Ditto for
{ and }.

The missing ) or } is
nearly always right next to another ) or }.

To check if a block of code is balanced, count +1 for
every ( and -1 for every
). You should get back to 0 if the parentheses are
balanced. Ditto for braces.

I have proposed a solution to the balancing problem with a SCID that displays matching parentheses and braces in
different sizes and colours to make it easy to match them by eye.