Nasty code

Tags: java, code, testing, nasty, ugly,

Added: 2012-04-12T00:00

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;
}
}

Comments

Comment

The Constructor can be re-written as a single line public Integer(int i) { f (i < 1) { throw new IllegalArgumentException(); isBroken = (((i%400)<100) && ((i%4)==0)); } So init() sets isBroken to true if we are in the first 100 values of a Cycle of 400 (0..99) and the number is also exactly divisible by 4. Suppose 'i' was minutes. Some event will happen once every 4 minutes during the first 100 minutes, then never happen again for the next 300 minutes. Then the cycle starts over. Reminds me a little of Leap Year calculations. Do I win a prize?
Add a comment

Your IP:
Please enter 2826335 here: