Code for positive data values not negative
While reading Pat Kua's latest post about how coding a certain way can help you avoid certain classes of bugs I was reminded of a technique taught to me by a colleague with regards to writing functions/methods.
The idea is that it is more effective to code for positive data values rather than trying to work out all the possible negative combinations, since there are likely to be cases which we hadn't considered if we do the latter.
For example, given the following method outline:
1 2 3 | public void someMethod(int someValue) { } |
We might know that this method should only be allowed to take in non zero values. Therefore it makes more sense to code for this knowledge than to infer which values are not allowed.
The following code snippet…
1 2 3 4 5 6 | public void someMethod(int someValue) { if(someValue != 0) { // throw exception } // someOtherMethod(); } |
…would therefore be preferable to this code snippet…
1 2 3 4 5 6 | public void someMethod(int someValue) { if(someValue < 0) { // throw exception } // someOtherMethod(); } |
…since in the latter we are making the assumption that less than 0 is invalid whereas the actual requirement was for non 0 values to be invalid.
I know this is a highly contrived example but in theory this approach should prevent unexpected behaviour in our functions.
I have been following this approach since I was shown it and my first thoughts are that it leads to code which is more expressive and easier to write since we are working with what we know rather than trying to infer what we don't know.
I think that following a test driven approach would eventually lead to us writing code similar to this anyway, but it's an interesting idea to keep in mind.
I think you mean to throw an exception if someValue == 0 in the first example.
Pete
11 Dec 08 at 11:21 am
Impressive, today I spoke to Cammy about this coding aiming positive results, after reading Pat's post. What a coincidence!
Alexandre Martins
11 Dec 08 at 11:27 pm
[...] refactored the code to refer to what we know is valid rather than looking at the reverse which I think is much more difficult to reason about. public [...]
Coding: Keep method/variable names positive at Mark Needham
11 Jun 09 at 7:48 am