```if (cond) foo(a) else foo(b)``` or ```foo(if (c...
# codingconventions
h
Copy code
if (cond) foo(a) else foo(b)
or
Copy code
foo(if (cond) a else b)
2️⃣ 6
1️⃣ 4
k
2️⃣ if it's exactly this but if it gets any longer create a temporary variable for the argument.
h
my current case:
Copy code
override fun MyRangeClass.toString() = buildString {
    if (startIsClosed) append("[") else append("(")
    append("$start, $end")
    if (endIsClosed) append("]") else append(")")
}
I feel like this is short enough that it doesn't justify a temporary variable, and long enough that it feels crowded as an argument
k
Hmm if the function you're calling has a side effect instead of a return 1️⃣ feels better somehow.
m
Whereas I was about to say I'd prefer to see the
append
on it's own, so that I know that regardless of which branch the
if
takes, something is getting appended. And the
if
is just determining what it is. But definitely no general rule here. So
append(if(startIsClosed) "[" else ")")
t
Wouldn’t this whole block read better as:
Copy code
val startBracket = if (startIsClosed) "[" else "("
val endBracket = if (endIsClosed) "]" else ")"
append("${startBracket}${start}, ${end}${endBracket}")
👍 3
m
Yes, that reads better. I suspect it will use more memory as you're implicitly wrapping a Stringbuilder to create the string and then call append on the passed one. But unless this is called a lot, I'd stick with the most readable one. Intellij will suggest removing the '{}' in the String template, but I don't always listen. In this case, I think it's clearer to keep them.
h
Yeah, if I were to handle as so, I'd write:
Copy code
override fun MyRangeClass.toString(): String {
    val startBracket = if (startIsClosed) '[' else '('
    val endBracket = if (endIsClosed) ']' else ')'
    
    return "$startBracket$start, $end$endBracket"
}
foregoing the
StringBuilder
altogether
Would be nice if I could do
Copy code
val startBracket = startIsClosed && '[' || ')'
like you can in python, js, lua, etc, but I understand why you wouldn't want to add
falsy
to kotlin