Sunday, June 8, 2008

Common Idioms 1

Most mainstream programming languages are pretty bad at initializating and populating structured data. Let's say you want a Java list containing "a" and "b".

First attempt :

List<String> a = new ArrayList<String>();

Pretty bad signal-to-noise ratio.

Second attempt :
List<String> a = Arrays.asList(new String[]{ "a", "b" });

Slightly more readable, but allocates a useless intermediate array.

Third attempt :
List<String> a = Arrays.asList("a", "b");

Much more readable, but doesn't work if you want a set rather than a list : there's no Arrays.asSet().

Here's the OptimJ version :
ArrayList<String> a = { "a", "b" };
HashSet<String> s = { "a", "b" };

But nausea quickly kicks in when you try to instanciate imbricated collection. A cooking recipe may be seen as a list (ordered) of sets of tasks (unordered because they can be done in parallel).

First attempt :
  List<Hashset<String>> irishStew = new ArrayList<Hashset <String>>();
  HashSet<String> set1 = new HashSet<String>();
  set1.add("Mince the meet");
  set1.add("Mash the potatoes");
  HashSet<String> set2 = new HashSet<String>();
  set2.add("Cook in oven");

Wow! This is called write-only code. Think about having to maintain pages of similar code written by an summer intern two years ago.

Second attempt :
... ?

The asList doesn't work because it requires expressions, and the code that builds our sets is a sequence of statements, not an expression.

Here's the OptimJ version :
  ArrayList<HashSet<String>> irishStew = {
    { "Mince the meet", "Mash the potatoes" },
    { "Cook in oven"}

Do you feel more confident now taking this code maintenance assignment ?

No comments: