Sacrificing Readability for Cleverness

I was looking at some code in the Three20 library when I came across this:

BOOL TTIsKeyboardVisible() {
  // Operates on the assumption that the keyboard is visible if and only if there is a first
  // responder; i.e. a control responding to key events
  UIWindow* window = [UIApplication sharedApplication].keyWindow;
  return !![window findFirstResponder];
}

The last line had me scratching my head as it has a double negation. While this looks like a mistake, it isn’t; this is a developer being clever. Let’s break down the line:

[window findFirstResponder]

This returns a nil value or a non-nil value. If we then negate it the result is YES if the firstResponder is nil and NO if the firstResponder is non-nil. If we negate it again, the rest is NO if the firstResponder is nil and YES if the firstResponder is non-nil. So, the bottom line is:

return [window findFirstResponder] != nil;

Why did the developer use the hard to read !![window findFirstResponder] when [window findFirstResponder] != nil is much more readable?

(We’ll ignore the fact that initial assumption is not always valid; I believe there are cases where the firstResponder isn’t a text field. Using keyboard notifications is the way to tell if a keyboard is visible.)

Writing clever code like this drives me insane as there is no reason to take shortcuts; a few extra characters isn’t the end of the world and the next person that reads the code has to closely examine the syntax to ensure that the !! isn’t an error.

2 Replies to “Sacrificing Readability for Cleverness”

  1. If you pair a Bluetooth keyboard to an iPhone, you can have a text field become first responder, but there will be no on-screen keyboard, so this three20 code does appear to be making an invalid assumption.

    1. Thanks for identifying one of the cases where the assumption fails. One of my colleagues pointed out that this idiom comes from assembly which I highly don’t most iOS developers have touched recently, if ever.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.