New Location

My website has moved to http://www.jasonwhaley.com. Please visit there for the latest and only remain here for legacy content.

Thursday, January 8, 2009

JavaFX "+" operator works like it ought to

This morning I took off to the coffee shop with the intention of learning a bit of JavaFX. I have some free time this AM so I figure this would be a good chance to get started on the tutorials provided by Sun, which is also how I initially learned Java.

One thing I noticed right off the bat, after dinking around for no more than 10 minutes, is that Sun got usage of the "+" operator correct, in my opinion, unlike it did with java. In other words, I hate the fact that in java the "+" operator gets used for mathematical addition AND string concatenation. I dislike this for two (well documented) reasons:
  1. String concatenation when performed in a loop, results in allocation of lots of unnecessary objects
  2. It leads to unexpected results when concatenating numbers and Strings and the programmer did not think to use String.valueOf() or the toString() method of the wrapper class of a primitive.
For instance, take this snippet of java code:

public class Main {
public static void main(String[] args) {
String ten = "10";
Integer five = 5;
Integer two = 2;
System.out.println(ten + five + two);
System.out.println(two + five + ten);
}
}

With the resultant output of:
1052
710
Because of the order of operations, both of those lines with println produce "correct" results, but probably not the expected results of a developer who would write such a line. Any java developer worth their salt will know not to do anything of the like... but that did not stop a senior developer at my employer, who has very strong kung-foo, from making that very mistake when he was tired and hurried.

The language spec writers for JavaFX script apparently got wise and corrected this. For instance, the following in JavaFX Script
function add(foo: String, bar: Integer) {
var result = foo + bar;
println("{foo} + {bar} = {result}");
}
results in the following compile time error
+ cannot be applied to strings. Use a string expression "{foo}{bar}"
The fact that JavaFX Script doesn't allow concatenation between a String and a non-String type unless you use an actual String expression such "{foo}{bar}", thus making the type conversion to a String explicit and not implicit, is a win, in my opinion.

No comments: