Negativity
Warning: I wrote this blog in 2017. That is a long time ago, especially on the internet. My opinions may have changed since then. Technological progress may have made this information completely obsolete. Proceed with caution.
Earlier today I tweeted:
I want to elaborate on this using more than 140 280 characters. The situation where I tend to do this is when I come upon code like this:
function processStuff(stuff) {
if(stuff.length > 0) {
//this is basically the whole function
doStuff();
//seems wasteful to indent this stuff
doMoreStuff();
//maybe another 100 lines of code
return whatever;
}
else {
//throw an exception or return an error message or print an error message or something like that
}
}
Two problems:
- The majority of the code is indented twice.
- The else clause is very far from the corresponding if clause.
So the solution is to refactor so that the current else clause is at the top
function processStuff(stuff) {
if(stuff.length == 0) {
//throw an exception or return an error message or print an error message or something like that
}
//this is basically the whole function
doStuff();
//look it doesn't have an extra unnecessary level of indention now!
doMoreStuff();
//maybe another 100 lines of code
return whatever;
}
The problem now is that the before and after this refactoring is not strictly identical. The negation of stuff.length > 0
is stuff.length <= 0
, not stuff.length == 0
. The first code would have gone through the error condition if stuff.length
is negative, but the refactored code won’t.
Now, I know that the length of an array will never return a negative in any programming language I’ve ever heard of. But, like I tweeted, what if it does?!
I want to ensure that I don’t break anything by refactoring. And it’s also not going to hurt anything if I write stuff.length <= 0
. But then I wonder what the next person to see my code will think. “Is there some reason this idiot1 thought array length could be negative?”
And I go through this thought process everytime I encounter this situation, mentally debating the pros and cons, instead of just accepting that it doesn’t matter and moving on.