Friday, April 11, 2008

Java's arithmetic operators

Here's a weird little one that confused me at first:

 @Test
public void testWeirdArithmeticOperators() {
double a = 1.0 / + + + 2.0;
assertTrue(0.5 == a);
String s = + + + + 0 + "abc" + "def";
assertEquals("0abcdef", s);
}


After playing about for a bit, switching some +es to -es and vice versa, I realised that the effect is that each + or - symbol could be rewritten as follows:
+ -> (+1)*
- -> (-1)*

So that the expression "+ + + 2.0" becomes "(+1) * (+1) * (+1) * 2.0" = 2.0, and the expression "- + + 2.0" becomes "-1 * +1 * +1 * 2.0" = -2.0. Thus, the sign of the result is negative for an odd number of - symbols and positive for an even number.

Seems a little pointless, but I suppose the logical way to see it is:
- + - x = - (+ - x) = - (+ (-x)). It makes sense then that the parser would accept it, but in it that form it looks wrong to (my) human eye.

Also, in writing this post I noticed that JUnit's assertEquals doesn't really like doubles:
assertEquals(0.5, 0) passes, as does assertEquals(Double.valueOf(0.5), Double.valueOf(0.0)) and other combinations. That's why I needed to use assertTrue(...) and == above. Huh.

Tuesday, April 01, 2008

the poor man's breakpoint

Since Eclipse is kind of very ridiculously slow betimes, I tend to avoid making it do too much work, for fear of it getting stuck in a rut and slowing down. Partly because my work machine is pretty much a doorstop, for the purposes of working with Eclipse (512mb RAM just doesn't cut it, if you want a browser and other apps open at the same time - I had to stop using the latest Opera snapshots while coding, as they use too much RAM at the moment, compared to Firefox 3.0b4).

So instead of running tests/etc in the debug perspective and adding breakpoints where I want to stop (if that block of code is executed), I've taken to doing things like this instead:
throw new RuntimeException("FUCK");
This means I get a stack trace showing how we got to the current state, which is often enough to realise what the problem is (at least, it was just now; I saw that a method I didn't expect to be called was being called by a parser for poorly-formed XML messages. Until that point, I didn't realise the messages were now poorly-formed as they weren't before I swapped XMLSerializer for LSSerializer earlier today).
Also, it's easy to search and remove your debugging throws afterward, since they contain the reasonably memorable, short string "FUCK". Of course, you wouldn't want to forget about it and leave one in a currently unused (as far as you know) method, lest an end-user find that their application is throwing an exception because FUCK. :)

Perhaps a more subtle keyword could be selected (how about "Fire in the hole" or "Get to the choppa!")...