Skip to content
This repository has been archived by the owner on Dec 21, 2023. It is now read-only.

curly blackets in if-else expression #20

Open
voddan opened this issue Jun 9, 2016 · 3 comments
Open

curly blackets in if-else expression #20

voddan opened this issue Jun 9, 2016 · 3 comments

Comments

@voddan
Copy link

voddan commented Jun 9, 2016

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 ++
}
@yole
Copy link
Contributor

yole commented Jun 12, 2016

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).

@voddan
Copy link
Author

voddan commented Jun 12, 2016

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

@cypressious
Copy link

cypressious commented Oct 20, 2016

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants