How not to use Shortcut Evaluations
In my Jupyter notebook on Shortcut Evaluations here https://gitlab.com/data-science-with-julia/code/-/blob/master/short_circuit_evaluation.ipynb, I had tabled such an example for you to fiddle:
y = false # change this to true and false and see what happens y && println("Right side executed")
This might make you think to write programs like this:
print_stuff = true print_stuff && println("Stuff") # very bad way of programming
&& in the above example is used as some kind of condition branching like
if. This might seem appealing and really short and concise way of expressing thing, that is print something or so some operation like this:
a = 5 increment = false increment && (a += 1) # remove the paranthesis and see what happens, can you explain why? increment || (a -= 1) # remove the paranthesis and see what happens, can you explain why? println("a = ", a)
In the above example a gets incremented if
true, and decremented if
false. Well in programming terms this is bullshit. Absolute bullshit. Constructing these types of programs may not invite a frown from the Julia compiler, but will definitely invite frowns from a good programmer.
|| are not supposed to be used as conditional branching. They are used for logical operations. So as a responsible programmer / data scientist (who’s job is programming too), it’s your job to create readable, understandable and maintainable programs. So possibly you could write the above program as shown:
# The right way a = 5 increment = false if increment a += 1 else a -= 1 end println("a = ", a)
or like this:
# Right and bit concise way a = 5 increment = true increment ? (a += 1) : (a -= 1) println("a = ", a)
Personally I am against the concise way because it does not make the program good to read. It’s my opinion, using the
if and spreading the things over multiple lines makes a clear read I would say.
The Jupyter notebook for this blog is available here https://gitlab.com/data-science-with-julia/code/-/blob/master/how_not_to_use_shortcut_evaluations.ipynb.