Saturday, February 02, 2008

Safer Java: Think Positive

If you've ever developed software for X11, you probably stumbled over "unmap". For everyone else: If you wanted to make something in a X11 user interface visible, you'd set "unmap" to "false". A great way to interrupt work because we're not used to negative thinking. If I want to make something visible, I think "I set some attribute to true" not the other way round.

In Java, we have learned but some API still smells. Collection.isEmpty(), for example. With positive thinking, I think of collections with elements as "better" than one without, so I'd prefer Collection.hasElements() even though it's longer and boolean properties should use "is" instead of "has". Oh well. But it's simple to fall for the negative trap in your daily work as well.

If you find yourself stumble mentally when using a boolean API, refactor and turn it positive. Modern IDEs make this simple and you'll write more error-free code in less time. commons-lang offers isBlank() and isNotBlank for Strings which is a good example because you don't have to put a "!" negator in your if's no matter if blank is good or bad in your specific case and the JIT will inline the code anyway, so there isn't even a speed penalty (only a LOC penalty).

No comments: