Suppose we are using AVKit
and we have added a target
to our play/pause button to handle the playing/pausing of a track. Is it generally bad practice to use a ternary operator just for its side effect, such as below?
// (AVPlayer definition omitted)
@objc fileprivate func handlePlayPause() {
(player.timeControlStatus == .playing) ? player.pause() : player.play()
}
The main reason I am asking this is because of the fact that side effects modify the state of a program and I believe I might have heard that you should handle side effects carefully sometime during one of my first-year courses.
Personally, I use them when I want to set a value to a variable, depending on a condition.
For example, let’s say that if x == 42
, I want the variable y
to be true
. If x
is not equal to 42 , then the value of the variable y
is false
.
So, how do I write that? Just like this…
let y = (x == 42) ? true : false
For if-else
, I would argue and be against it.
Why? Take a look at this code:
var y = false
if (x == 42) {
y = true
}
So we can have something like this, assuming you want it to be in one line:
var y = false if (x == 42) { y = true }
Which is ugly and unnecessary, because we can write it like this:
let y = (x == 42) ? true : false
So much cleaner! We reduced seven (4) lines of code to just one (1) line.
Ternary operators are awesome, but they’re not always needed. Suppose you just want to execute a function, or do multiple operations. don’t use ternaries.