Short-Circuit Error

Developers are human. Humans err. This is just a short reminder to myself to never ever make the same mistake.

This is real (failing) production code I came across today…stripped to its bones:

screenshot_09.png

The developers intention was…

  • …to execute method(int a, int b, int c) three times (with different parameter values)…
  • …expecting  each method call to pass…
  • …and in case one of the methods returns false, to return an error.

Actually three different methods were called, but the idea is the same.

Unfortunately Java short-circuits boolean && expressions! Poor developer.
baby.jpg

(Image provided by fiat.luxury under Creative Commons)

The first call method(5, 5, 3) returns true which is negated (!) to false. Once the boolean expression contains false, there is no way it will ever change to true. It is absolutely irrelevant what the results of method(4, 2, 3) and method(7, 8, 33) are.

Therefore only method(5, 5, 3) gets executed. The two other calls are skipped. 

Instead of the expected…

screenshot_11.png

…the actual result is:

screenshot_10.png

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s