DEV Community

RedCreator37
RedCreator37

Posted on

To align assignments or not?

If you've looked at the code of some well-known maintained C/C++ open source projects, you may have noticed that whenever there are multiple variable assignments they tend to be aligned like this:

first_num      = 1;
second_num     = 2;
third_num      = 3;
fourth_num     = 4;
fifth_num      = 5;
some_other_num = 6;
Enter fullscreen mode Exit fullscreen mode

instead of

first_num = 1;
second_num = 2;
third_num = 3;
fourth_num = 4;
fifth_num = 5;
some_other_num = 6;
Enter fullscreen mode Exit fullscreen mode

This can sometimes also be seen in Makefiles (especially automatically generated ones). But speaking of Java, most IDEs will likely attempt to trim redundant whitespace by default.

So what do you think? Is this style relevant to Java as well?
Also, which one looks more readable to you?

Top comments (1)

Collapse
 
jingxue profile image
Jing Xue • Edited

It's certainly easier on the eyes when they are aligned, but IMHO the benefit is negligible or even irrelevant in a modern programming context.

In Java, it's preferred to declare a variable as close to where it is first used, instead of in the beginning of the block. Java developers are also encouraged to constantly refactor code into simpler and smaller methods. So overall there is less chance of having a long list of variable declarations anywhere.

Where we do have a list of variable declarations, most of them tend to be instantiating objects or calling methods, instead of assigning literal values. Java classes and methods tend to have much longer names, so aligning variables doesn't seem like an economic use of space and would mostly cause more unnecessary line wrapping.

Another practical annoyance from aligning variables is, when you need to add a new, longer variable, you'll have to realign all the variables before it. That messes up the commit diff and authorship on those lines. IMHO in programming these days, the readability of commits and line-based blame/annotate can be actually more important than that of the code itself.