Monday, February 1, 2016

Avoiding the Negative for Clear Code

My Auntie Pat Tern recently reminded me to avoid double negatives and use positive language as often as possible. So I looked through some of the code in my org and decided to share her advice with my developers. When we write conditional statements using NOT (or "!"), we are using negative syntax which is more difficult to understand than positive syntax. Here's an example written in negative syntax, then rewritten in positive syntax:

The conditions evaluate the same, but I find the negative syntax more difficult to read during code review and maintenance. Note that it can be improved upon further with a basic knowledge of String methods.

The first time I encountered super negative syntax, I thought the developers who used it were making a game of being abstruse.  But knowing that the two programmers were friends led me to discover that this was in fact a case of "cargo cult programming" where they were sharing and reusing a bad pattern because they hadn't taken the time to pick apart what the code needed to accomplish. Once they better understood what the code was doing, they learned to write it more clearly.

No comments:

Post a Comment