dagblog.
← Archive

Open debate: should we use every trick in the language?


I won't begin with the usual “the other day.” Let's say I happened across some interesting, rather tricky constructs in the code. The first uses instance initializers with an anonymous inner class, which gives you an interesting way to create and populate an object. The second is multiple declarations of a local variable, for want of a better term.

Instance initializer (copied from elsewhere — thanks, Martin)

Set s = new HashSet() {

 {

 add("x");

 add("y");

 add("z");

 }

};

Multiple declarations of a local variable (thanks, NkD)

public class Foo { 

 public void my(){

 {

 String var = "foo";

 System.out.println(var); 

 }

 

 {

 String var = "hoo";

 System.out.println(var);

 }

 

 String var = "bar";

 System.out.println(var);

 }

}

Personally, I think we should stop short of using every last trick the language's syntax allows. It makes code hard to read and can give less experienced programmers quite a puzzle to crack. Actually, you do not even have to look for someone less experienced. Ask the colleague sitting next to you whether the code above looks as though it will compile and what exactly it does.

I find the example with the instance initializer and anonymous inner class acceptable, and I even like it. The second looks to me like a workaround that lets you copy and paste your way through a method. Where the line falls between, say, concise code and an incomprehensible sequence of letters and other characters is of course a matter of taste. So I am curious what you think. Should we use every trick the language allows?

Medium version

Related articles

Related CZ Podcast episodes