Monday, June 4, 2018

WTF: Modulo the String way

I found this old code in one of our application:
DecimalFormat df10 = new DecimalFormat("0000000000");
String idStr = df10.format(peer.execid);
idStr = idStr.substring(4);
exec.execId = Integer.parseInt(idStr);
It takes an int, format it into a String padded with zeroes on the left, then strip away the first 4 characters. Then of course we turn it back into an int.

Knowing that the id is always positive, this code is completely equivalent to that one:

exec.execId = peer.execId % 1000000;