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:
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…
public void someMethod(int someValue) {
if(someValue != 0) {
// throw exception
}
// someOtherMethod();
}
…would therefore be preferable to this code snippet…
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.
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.