DEV Community

Cover image for Don't be a Bracist
Johannes Vollmer
Johannes Vollmer

Posted on

Don't be a Bracist

Trigger warning: This post assumes that racism should be avoided.

Despite being a student, I already know how time-consuming it can be to dig through other people's work. But there's a particular habit that makes reading code less awkward, and we all know it: Proper Formatting.

There are many online guides on how to format your code. Most IDE's even have a nifty tool that automatically formats your source files. But theres a tiny inconsistency which many of those tools and guides choose to ignore.

Common Brace Indentation

This post is all about the formatting of parantheses to group arguments and (curly) braces to group statements. JS, Java, C++, Rust, C and hundreds of other languages use these in a similar manner. Let's have a look at how braces are usually indented in Java:

// inside KittenFactory
public List<Kitten> getKittensByAge(int minAge, int maxAge, boolean useGloves){
    final Filter ageFilter = new AgeFilter(minAge, maxAge);
    if (useGloves) {
        ageFilter.useHands();
        if (ageFilter.hasAnyGloves()) {
            ageFilter.removeWatch();
            ageFilter.enableGloves();
        }
    }
    return this.getKittens(ageFilter);
}
Enter fullscreen mode Exit fullscreen mode

We start to see a pattern here: Closing braces are indented to the same level as their parent method head or if-keyword. Content inside braces is indented one level more than their parent keyword and closing brace. But now, let me throw that same code with an alternative indentation style at you (sorry, mobile phone users):

public List<Kitten> getKittensByAge(int minAge, int maxAge, boolean useGloves){
    final Filter ageFilter = new AgeFilter(minAge, maxAge);
    if (useGloves) {
        ageFilter.useHands();
        if (ageFilter.hasAnyGloves()) {
            ageFilter.removeWatch();
            ageFilter.enableGloves();}}
    return this.getKittens(ageFilter);}

Enter fullscreen mode Exit fullscreen mode

In case you are considering to write a comment about a missing closing brace, look again. It's right there. I hope you enjoy that feeling of confusion, because there's more:

public List<Kitten> getKittensByAge(int minAge, int maxAge, boolean useGloves){
    final Filter ageFilter = new AgeFilter(minAge, maxAge);
    if (useGloves) {ageFilter.useHands();
                    if (ageFilter.hasAnyGloves()) {ageFilter.removeWatch();
                                                   ageFilter.enableGloves();}}
    return this.getKittens(ageFilter);}

Enter fullscreen mode Exit fullscreen mode

Common Paranthesis Indentation

I feel your confusion and disrespect, yet I can sense a weird feeling of familiarity deep inside of you. It's because we all have seen it before, but not with braces, but with parantheses:

factory.getKittensByAge(0.2,
                        0.3,
                        user.glovesAreAvailableFor("Peter",
                                                   2017,
                                                   Location.of("Peter")));

Enter fullscreen mode Exit fullscreen mode

Heck, this formatting even was found in Oracle's formatting guide (officially outdated).

Wow.

Alternative Indentation

This style of indentation greatly reduces readability. The important source code moves more and more to the right, far away from all the other code. Also, you can see a bunch of closing brackets cuddling at the end. Imagine having to debug a missing parantheses in such a function call. It's a mess. But fear not! There are alternatives! And we already use them, but with braces, and not with parantheses. Have a look:

factory.getKittensByAge(
    0.2,
    0.3,
    user.glovesAreAvailableFor(
        "Peter",
        2017,
        Location.of("Peter")
    )
);

Enter fullscreen mode Exit fullscreen mode

Yep, it's that simple. This style has some remarkable benefits: Linebreaks actually move code back to the left, and you can easily see, which closing bracket belongs to which function call. That's why we use that style for braces, after all. Also, having one special formatting rule less seems to be easier anyway.

That same indentation style can also be applied to if-statements and function parameter definitions:

if(
    this.factory.filterType.hasGloves()
    && this.user.canUseGloves() // '&&' is important, so place it left
){
    factory.enableGloves();
}

Enter fullscreen mode Exit fullscreen mode
public void setAllFieldsAtOnce(
    double fluffiness,
    String name,
    double minAge,
    double maxAge,
    // ...
){
    this.fluffiness = fluffiness * Double.MAX_VALUE;
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

So, please don't be a bracist. Pay parantheses the same respect as braces. They deserve it! In the end, they are both used to group elements. Plus, your code will be much more readable.

I am aware that you may not be in the position to change the coding style at your company, but you can at least share this idea with friends and coworkers.

I hope you enjoyed my first post ever on dev.to!

Top comments (14)

Collapse
 
jasongabler profile image
Jason Gabler • Edited

Awesome title :D

Over the years I've relaxed my brace and paren attitudes. If someone has been consistent, after a few minutes I can get the feel of their style and focus on the logic of their code and get hacking.

What still ties me up in knots, and this is about my own coding habits, not other people's code, is long lists of function parameters. I can never decide which is more appealing to the eyes, easier to read, and all while conserving vertical space. So...

public function someBigLongFunctionNameThatTakesLotsaSpace( $paramOne, $paramTwo, $paramThree, $paramFour) {
...
...
}

or

public function someBigLongFunctionNameThatTakesLotsaSpace( $paramOne,
                                                            $paramTwo, 
                                                            $paramThree,
                                                            $paramFour) {
...
...
}

or

public function someBigLongFunctionNameThatTakesLotsaSpace( $paramOne, $paramTwo, 
                                                            $paramThree, $paramFour) {
...
...
}

or

public function someBigLongFunctionNameThatTakesLotsaSpace(
    $paramOne,
    $paramTwo, 
    $paramThree,
    $paramFour) {
...
...
}
Collapse
 
paayaw profile image
Derek Owusu-Frimpong

Probably the last one is better. For me, I try to prevent my eyes travelling far to the right. That makes me lose focus easily.

Collapse
 
johannesvollmer profile image
Johannes Vollmer

Agreed. Also, I don't mind having multiple parameters in one line, but I really need them to be on the left side.

Collapse
 
johannesvollmer profile image
Johannes Vollmer

Thanks :D

Collapse
 
maxx0r profile image
Max

Another readability hint, don't pass operations as arguments (the glovesAreAvailable). I've stopped doing this a long time ago and it really helps maintenability.

It's nitpicking, I know. But it really helps writing clearer code

Collapse
 
johannesvollmer profile image
Johannes Vollmer

I agree for languages where named arguments are not available.

Collapse
 
bgadrian profile image
Adrian B.G.

In Go we don't have problems like these, we're Zen 😎.

Collapse
 
johannesvollmer profile image
Johannes Vollmer

I'll not that familiar with go - could you please explain how go solved that syntax problem? :)

Collapse
 
bgadrian profile image
Adrian B.G.

Sure, the core dev team, who made the language, also made tools for static analysis,linter, code formatting and incorporated some of the rules in the compiler too, this you get these advantages:
blog.golang.org/go-fmt-your-code

easier to write: never worry about minor formatting concerns while hacking away,
easier to read: when all code looks the same you need not mentally convert others' formatting style into something you can understand.
easier to maintain: mechanical changes to the source don't cause unrelated changes to the file's formatting; diffs show only the real changes.
uncontroversial: never have a debate about spacing or brace position ever again!

A Go "proverb" is "Gofmt's style is no one's favorite, yet gofmt is everyone's favorite", meaining each dev will not like something about the Go standard way, but overall you like it's benefits, because everyone obeys it.

Thread Thread
 
johannesvollmer profile image
Johannes Vollmer

Cool. But how does it indent function calls with many parameters? :D

The rust language has a similar thing, but unfortunately, it will indent many arguments far to the right.

Thread Thread
 
bgadrian profile image
Adrian B.G.

That's the beauty, it doesn't matter and we do not care. We solve problems, we are engineers, coding is just a 20% of our jobs and we shouldn't focus on things that the IDE should do for us.

Unless someone makes a PR to the official Go tool and convince the community that is better his way.

Collapse
 
antero_nu profile image
Antero Karki

I tried closing braces at the end of the line, 1st alternative syntax, made the code look more "pythonic". Soon gave it up though because of the inconvenience of always having to fix code when removing or adding lines, and removing lines with braces wasn't just a mark line then push backspace anymore if you still needed the braces.

Collapse
 
timsev profile image
Tim Severien

Thankfully, I've rarely seen the parenthesis indentation you consider common, so hopefully I won't have to share this article too often ;)

Collapse
 
johannesvollmer profile image
Johannes Vollmer

That's great :)