Tuesday, June 22, 2010

Using String.format to easily output arguments like .NET or C++ allows

When I started programming using Java I was surprised when I didn't find an equivalent to the functionality provided by String.format in .NET (or similar functions in C++) which allowed you easily to mix string output and variables without having to deal with manually concatenating the data which to me always makes the code look very very ugly. For example, if you wanted to output the arguments passed to a function in .NET then you could do something like the following

function doSomething(arg1 as String, arg2 as String, arg3 as string) as Object
    logger.finest("Arguments passed are arg1: {0} arg2: {1} arg3: {3}", arg1, arg2, arg3)
    ...
    ...
end function

If we executed the above function as follows:

doSomething("foo", "bar", "donkey")

then the output would be:

Arguments passed are arg1 foo arg2 bar arg3 donkey

To me this solution helps to minimize the compexity of the code and just looks pretty.

In java traditionaly I would traditionally have implemented the same functionality as follows:

function Object doSomething(arg1 as String, arg2 as String, arg3 as string){
    logger.finest("Arguments passed are arg1: " + arg1 + " arg2: " + arg2 + " arg3: " + arg3);
    ...
    ...
}

Besides always having to deal with eclipse trying to insert extra " characters it just looks ugly (especially if you are opening the file in something that doesn't do syntax highlighting.

Thankfully today I discovered that as of Java 1.5 the String.format function does provide the same functionality as .NET (joy)

The code can now be written as:

function Object doSomething(arg1 as String, arg2 as String, arg3 as string){
    logger.finest("Arguments passed are arg1: %s arg2: %s arg3: %s", arg1, arg2, arg3);
    ...
    ...
}

Now doesn't that just look beautiful.

More information can be found at: http://www.rgagnon.com/javadetails/java-0463.html