Maintainable Code #1

This code snippet (FirJvmStaticChecker.kt:72) caught my eye while digging into Kotlin codebase:

if (
    container !is FirClassSymbol ||
    container.classKind != ClassKind.OBJECT ||
    !container.isCompanion() && containerIsAnonymous
) {
   ...
} else if (
   ...
) {
   ...
}

Kotlin expression precedence states that logical and (&&) has a higher precedence than logical or (!!), therefore !container.isCompanion() && containerIsAnonymous is evaluated befire container !is FirClassSymbol and container.classKind != ClassKind.OBJECT are evaluated.

Not everyone has internalized Kotlin’s precedence to the code owner’s degree and may require multiple passes to be confident that s/he truly understands the snippet’s intent. In all honesty, I pride myself on my ability to read code and I had to make multiple passes. It’s just not blatantly obvious.

I prefer my code to be explicit in conveying the code’s intent and (hopefully) reduce misinterpretation and, more importantly, avoid breaking changes based on a misinterpretation. Adding parentheses explicitly conveys intent without impacting functionality:

if (
    container !is FirClassSymbol ||
    container.classKind != ClassKind.OBJECT ||
    (!container.isCompanion() && containerIsAnonymous)
) {
   ...
} else if (
   ...
) {
   ...
}

Every programming language has its nuances which provides tricks and shortcuts that experienced engineers take, often to show how smart s/he is. It’s not an issue when s/he is the sole code maintainer, but that is much less likely today. I am not advocating writing code for the simplest and most inexperienced engineer, but there are times when simple changes enhances understanding. Here, adding two parentheses goes a long way towards assistance future maintainers.