Do you write incremental operators in loops and conditions?

Question from keldranase#4427

The question is more about coding style for production grade code. Do you write incremental operators in loops and conditions? Consider two pieces of merge algo. What version is better?

            if (list.get(left) < list.get(right)) {
                result.set(writePtr, list.get(left));
                ++left;        // separated incremetns
                ++writePtr;   
            } else {
                result.set(writePtr, list.get(right));
                ++right;
                ++writePtr;
            }
           if (list.get(left) < list.get(right)) {
               result.set(writePtr++, list.get(left++));    // increments inside things
           } else {
               result.set(writePtr++, list.get(right++));
           }

Another example is something like this:

while (someCounter-- > 0) {
  // do something
}

Or more verbose, like this:

while (someCounter > 0) {
  // do something
  --someCounter;
}

Most increments are effectively just iterators. So if you are doing anything other than (int i = 0; i < container.size(); i++) then the best code quality would come from working with the iterator/stream abstractions.

However the first one is the one I would go with, with the caveat that I would use left++ instead of ++left.

No one remembers operator precedence order except C programmers, so separating mutation from assignment/passing of values is best. Everyone does thing++ usually and, outside of a context where you are passing at the same time you are changing it, it doesn't matter.


<- Index