not sure? write a test

I learned this lesson from a colleague some years ago, but it’s worth reiterating. If you have a question about how a certain aspect of a programming language or library behaves, then it’s usually quicker to write and run a small test which demonstrates, than it is to read the documentation to try and figure it out. (And that assumes the documentation is good enough, which is not always the case).

For example, today I’m not sure what happens when I call a Java varargs method with no values for the varargs part. So I write a test class like this:

package org.ethelred.scrapbook;
 
public class VarargTest
{
	public void testMethod(String... args)
	{
		if(args == null)
		{
			System.out.println("args is null");
		}
		else
		{
			System.out.println("args is a " + args.getClass().getName() + " with size " + args.length);
		}
	}
 
	public static void main(String[] argv)
	{
		VarargTest testObj = new VarargTest();
		System.out.println("no args call:");
		testObj.testMethod();
 
		System.out.println("one args call:");
		testObj.testMethod("first");
 
		System.out.println("two args call:");
		testObj.testMethod("first", "second");
	}
}

(Actually this covers slightly more than my original question, but it is worth being thorough.) The program produces this output:

no args call:
args is a [Ljava.lang.String; with size 0
one args call:
args is a [Ljava.lang.String; with size 1
two args call:
args is a [Ljava.lang.String; with size 2

So the answer to my question is that with no values, the parameter appears as an empty array.

There are caveats to this approach. With Java it works well because the environment is well specified and consistent, and also in this case I know that the resulting software is only going to be run in our own server environment, so I don’t have to worry about other implementations. In other languages there may be competing implementations that differ – for example for client-side Javascript you would have to run tests in different browsers and they might have different results.

If you like this approach you could even use it to learn a language. It works well for Ruby because the language and some of its libraries are not particularly well specified.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*