A Leaf, a Label, and a Shortcut
An embossed leaf makes a lovely field card, but the label matters too. I want to mark cards whose observation starts with a question mark: a small reminder that the identification needs another look. Some cards have no observation yet, though, so checking their first character takes a little care.
Both of these programs print the same result:
needs review: true
needs review: false
Here’s the OCaml version:
let needs_review note =
String.length note > 0 && note.[0] = '?'
let () =
Printf.printf "needs review: %b\n" (needs_review "? maple");
Printf.printf "needs review: %b\n" (needs_review "")
The first test asks whether there is a character to inspect. Only if that answer is true does && evaluate the second test. An empty string therefore never reaches note.[0], which would otherwise raise an exception.
Kotlin makes the same decision in much the same way:
fun needsReview(note: String): Boolean =
note.isNotEmpty() && note[0] == '?'
fun main() {
println("needs review: ${needsReview("? maple")}")
println("needs review: ${needsReview("")}")
}
This is short-circuit evaluation: once the left side of an AND is false, the whole expression must be false, so the right side is skipped. OR works in the other direction: a true left side makes the right side unnecessary.
Order is part of the design. Putting the character check first would make the empty card unsafe again. And if the skipped expression writes a field note or updates a counter, that action will not happen. A shortcut is useful precisely because it does less; the trick is to make sure the omitted work is truly optional.