views:

161

answers:

3

I'm calling a Java method from another language (R). Some of the parameters are optional in my R function. What's the best way to handle uninitialized parameters in a Java method? (Ideally without using exception handling...)

Edit: Follow-up based on the first response:

"2.Initialize with predefinied defaults and continue"

How can I check if something isn't initialized?

Here's some pseudo code of the approach I was hoping to use:

public static void test(int i) {
 if(!is.initialized(i) {
  i = 0;
 }
 // Do stuff with i
}

Edit 2: Overloading seems like a lot of work. I'd rather have one method and handle each case with defaults. That said, I'm not an expert and would love to learn what the best practice is here.

+1  A: 

Depends.

  1. Display kind of informal message to user how to use the program properly and exit.
  2. Initialize with predefinied defaults and continue.
  3. Throw IllegalArgumentException.

Either way, you need to document it clearly.

BalusC
@BalusC - I don't think these suggestions make sense. He is asking about invoking a Java method, not running a Java application. Java does not support the notion of an uninitialized parameter.
Stephen C
+2  A: 

Since Java doesn't support default parameters, I would recommend using overloaded versions of the method that cover the optional parameters, although depending on how many optional parameters you have, this could get messy.

EDIT: As suggested in a comment, you could use varargs to collect the variable number of parameters and then include the logic for handling the different combiantions of compulsory and optional parameters inside the method.

This would only require one method. See this Varargs documentation

Using varargs, you could use similar logic as in your pseudocode.

chrisbunney
Thanks Chris! After looking at this further, your first recommendation seems like the best.
griffin
Credit should also go to Greg Hewgill who addressed your comment about overloading seeming like a lot of work; I took it for granted that you knew how to do overloading but you did say you're not an expert
chrisbunney
+2  A: 

Overloading is not a lot of work. Generally you would do something like:

public static int test(int i, int j) {
    // detailed processing here
}
public static int test(int i) {
    return test(i, 0);
}
public static int test() {
    return test(0, 0);
}

In this way, you only need to implement your processing logic once, and then have short one-line methods that fill in whatever is missing and pass control to the method that does the real work.

Greg Hewgill
Thanks Greg! That really clarified it for me. I'll use overloading.
griffin