DEV Community

Discussion on: short-circuits && clean code

Collapse
 
dwd profile image
Dave Cridland

I think it comes down to idiom.

Idioms in programming are miniature patterns that are commonly used. If there's more than one way to do something, one is normally the preferred idiom, either in the language community or else the project you're working in.

For example, you might see this in Perl:

fopen(my $fh, "filename") or die "Cannot open file";

That's a shortcut for an if statement, there - but that construct is very often used for error handling. Sometimes for default values. Rarely for anything else. This seems like a reasonable guide.

Also, I'd forgotten Perl, when I came to write that.

Following idioms is useful for two reasons. Firstly, it makes code more readable to one versed in common practise. Secondly, it has often been arrived at my lots of people finding out what worked effectively and what didn't.

errno ? fprintf(stderr, "Error: %s\n", strerror(errno)) : 0;

C has the ternary operator as well. If you ever do code like this I will hunt you down. It's possible to write this code (I think), and it's not a short-circuit (more on that later). But it's absolutely not idiomatic. The ternary operator is only ever used as part of an expression (and usually the expression itself), most often in a function argument list.

values = [x if x < 4 for x in arr] or None

You can do some pretty odd things with Python shortcuts. Here, selecting everything lower than 4 in an array, and if there's nothing then return None (a NULL-like object). Again, good for default values.

test -f /etc/passwd || echo "Password file missing!" >&2

Assuming I still recall shell programming, that's a fairly common shortcut idiom there, too, for error handling.

But I don't think you want to confuse this with short-circuit evaluation. Yes, this certainly relies on short-circuits to work, but you can (and absolutely should) use short-circuit eval always:

if (flag && expensive_operation()) {
  // Do something
}

That's only running the expensive operation if flag is set. Now, assuming that expensive_operation() has no side-effects - and it shouldn't, if we're following good practise - then putting these terms the other way around would have the same behaviour, but it'd run slower.

So short-circuits are fine, and to be encouraged. Shortcuts based on them are a matter for idiom, and should be used sparingly.

Collapse
 
rpalo profile image
Ryan Palo

This is a very good answer. Personally, I really like how short-circuiting reads, coming from a bash/ruby/python background, but I could see the value of using them only in the simplest of cases if others ever need to look at your code.