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).

One Response to Safer Java: Think Positive

  1. […] Another great example why you should prefer positive logic. […]

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s

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

%d bloggers like this: