&. |

A software developer’s musings on software development

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 have wasted too many hours of my life debating whether to write "if(somearray.length == 0)" or "if(somearray.length <= 0)". I mean, I know .length could never return a negative... but what if it does???

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:

  1. The majority of the code is indented twice.
  2. 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.


  1. Believe me, the last programmer was always an idiot. Especially when it was me.