HiveBrain v1.2.0
Get Started
← Back to all entries
debugMinor

Reporting success or failure of a child process

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
reportingprocesssuccesschildfailure

Problem

The variable result is an integer representing the exit code of a command line process that was run via Groovy code. An exit code of 0 means the process was successful and an exit code from 1-255 means a failure. Then this line is executed:

println result ? "The command failed." : "The command succeeded."


What's happening here is that result is being coerced to a boolean (nonzero is true, zero is false) and then the ternary operator is used to determine which message to print, telling the user if the command succeeded or failed.

Is this fine in the context of the Groovy language, or is this going a bit too far with implicit magic?

Solution

In your original post, you wrote

The variable result is an integer representing the exit code of a command line process that was run via Groovy code. An exit code of 0 means the process was successful and an exit code from 1-255 means a failure. Then this line is executed:

println result ? "The command failed." : "The command succeeded."

I find it interesting you had to explain it so much. I imagine if this were real code you may have to attach a similar code comment.

Personally I prefer to write code that requires no comments, if possible, and no explanation, by using well-crafted symbols. So for example if you wrote it as

boolean success = (exitCode == 0);
println success ? "The command succeeded." : "The command failed.";


...you wouldn't have to explain that a exit code of 0 indicates success, and it wouldn't require a second glance to figure out the reversed ternary expression.

Any compiler worth its salt will optimize out the working variable and emit exactly the same executable code, so the increased readability costs you nothing.

Code Snippets

boolean success = (exitCode == 0);
println success ? "The command succeeded." : "The command failed.";

Context

StackExchange Code Review Q#34016, answer score: 5

Revisions (0)

No revisions yet.