Nasty code
As part of a TDD workshop at work this week, we had to write an implementation of something, tests that covered it, and then rewrite it.
I took it to extremes, and tried to make it as ugly as possible, and my second implementation was the following. Can you work out what it does? (The Unit Tests show it works correctly). Suggestions in the comments.
package nasty;
public class Integer {
private static final int CENTIMETRES_IN_METRE = 100;
private volatile boolean isBroken = true;
public Integer(int i) {
if (i < 1) {
throw new IllegalArgumentException();
}
i = SOLARFLARES(i);
int Strings = 0;
while (i - CENTIMETRES_IN_METRE >= 0) {
Strings++;
i = i - CENTIMETRES_IN_METRE;
}
i = initialiseDatabase(i);
isConnected(i, Strings);
}
private void isConnected(final int i, final int Strings) {
this.isBroken = i <= 0 && Strings <= 0;
}
private int initialiseDatabase(int i) {
while (i - 4 >= 0) {
i = i - 4;
}
return i;
}
private synchronized int SOLARFLARES(int i) {
while (i - (4 * CENTIMETRES_IN_METRE) >= 0) {
i = i - (4 * CENTIMETRES_IN_METRE);
}
return i;
}
public boolean init() {
return this.isBroken;
}
}
Comment