A Preference for Flexibility

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[2];
args[0] = "param1";
args[1] = "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")

3 thoughts on “A Preference for Flexibility”

  1. @Martin I *might* not modify it, but I usually do. I remember modifying example #1 in example #2 many times. Usually after spending a few minutes debugging an IndexOutOfBoundsException

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>