views:

94

answers:

2
    public Subclass(String[] parameters) throws IllegalArgumentException {
    super("Rectangle", Double.parseDouble(parameters[0]),
                 Double.parseDouble(parameters[1]),
                 90,
                 Double.parseDouble(parameters[2]),
                 Double.parseDouble(parameters[3]));
    if(parameters.length != 4) throw new IllegalArgumentException(
        "bla, bla");
    if(parameters == null) throw new IllegalArgumentException(
        "bla, bla");
    }

I would like to put these 2 if statements before calling super-constructor. I know that I can't do that, so what's the painless way to do that kind of parsing of parameters (throwing Exception) before calling super()?

+2  A: 

You could create a factory pattern (for example an abstract factory) to create a factory object from which new instances are obtained. The factory class method to obtain new instances could then throw bad argument exceptions before calling the (private) constructor of the real subclass.

You could also use a Builder pattern to verify parameters before creating and returning a new instance. You create a builder object (often an inner class, so that it has access to the outer class's private constructor etc.), set its properties and call a build() method - that method can then do any verification you need before returning you a new instance.

Brabster
Thank you very much!
an_ant
+5  A: 

Declare a validation method taking String[] and returning it:

private static String[] validate(String[] param) {
    // do validation here
    return param;
}

And call it when using param first time

super("Rectangle", Double.parseDouble(validate(param).parameters[0]),

This trick solves problem quickly, but, as another poster noted, sometimes it's better to refactor your API (like creating a factory method).

Nikita Rybak
Validate should be declared with "throws"? Nvm, I'll compile and see :). Thanks!
an_ant
@make - `IllegalArgumentException` is unchecked, so `validate` does not need a `throws` list.
Stephen C
@Stephen C - thank you very much! Forgot about that!
an_ant