kotlin-style-guide icon indicating copy to clipboard operation
kotlin-style-guide copied to clipboard

curly blackets in if-else expression

Open voddan opened this issue 9 years ago • 3 comments

if-else

A one-line if-else expression should not use curly bracket blocks:

val max = if(a > b) a else b

A multiline if-else may not to use blocks if both of the branches consist of one-line expressions:

if (a > b)
    println("a")
else
    println("b")

If at least one of the branches has 2 or more statements, both branches should use blocks:

// Good
if (a > b) {
    return a
} else {
    println("else")
    return b
}

// Bad
if (a > b)
    return a
else {
    println("else")
    return b
}

raw if

If the branch of a raw if is the last in the control flow, for example it returns or throws, do not use a block:

if(x > 100) return

if(x < 1000) 
    throw IndexOutOfBoundsException

If the single branch of a raw if is not terminal, use a multi-line code block:

if(x < 100) {
    x ++
}

voddan avatar Jun 09 '16 15:06 voddan

Not entirely sure about the terminal/non-terminal rule. I see where you're coming from, but I don't believe it will be followed in practice (always putting curly braces around an increment might be too verbose for people's taste).

yole avatar Jun 12 '16 09:06 yole

Even without curly braces, an empty line must be spend after the if in order to keep it readable:

if(x < 100)
    x ++

println(x)

So there is no gain in omitting the braces from the LOC point of view

voddan avatar Jun 12 '16 09:06 voddan

I personally follow the following rule:

Either put the single expression on the same line or use curly braces.

//good
if (x < 0) return

//good
if (string.isEmpty()) x++

//bad
if (foo())
    continue

//good
if (x >= 0 && y >= 0) {
    doSomething(x, y)
    return
}

If the line becomes too long, use curly braces, too.


The most important thing is to never write

if (foo())
    bar()
    baz()   //this is not guarded by foo()

which is known as the famous Apple goto bug.

cypressious avatar Oct 20 '16 07:10 cypressious