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.