I came upon this example in an otherwise very good book. One example tried to test a
main method by passing arguments:
String args = new String; args = "param1"; args = "param2"; MainApplication.main(args);
Whenever I write in this kind of code, I always prefer to create an array instead:
List<String> list = new ArrayList<String>(); list.add("param1"); list.add("param2"); MainApplication.main(list.toArray(new String[list.size()]);
It’s a bit more verbose, but I find it offers a lot more flexibility as adding new parameters is simply a matter of adding a new element to the list. In the first example, adding a new parameter requires two steps : 1) modify the size of the array and 2) initialize an element of the array to the desired value.
I do whatever I can to remove a step, as small as it seems.
Modifying all the indexes is also a lot less fun when you need to add an element at index 0. And of course you’ll eventually copy/paste one line of the array and forget to modify either the size of the array or the index.
Using a list is a small improvement but in the long run, small things make the code a lot more maintainable.
PS : a friend noted that if you already use Google Collections (now Guava), you can get even more elegant code with
list = Lists.newArrayList("param1", "param2")