How to check that the set of variables is not null before proceeding

I have a class that extends org.apache.ant.tools.Task. This class has 5 variables that are set via public setters:

private String server;
private String username;
private String password;
private String appname;
private String version;
private String file;

      

And then there is a public execute () method that is called by ant:

public void execute() throws BuildException {
    checkArgs()
    ... // my execute code goes here
}

      

Before doing the run, I want to check that none of my required variables are null, and if so, throw a BuildException () describing the problem, so the user back in ant has some idea of ​​what is wrong:

private void checkArgs() {
    if (server == null) {
        throw new BuildException("server cannot be null.");
    }

    if (username == null) {
        throw new BuildException("username cannot be null.");
    }

    if (password == null) {
        throw new BuildException("password cannot be null.");
    }

    if (file == null) {
        throw new BuildException("file cannot be null.");
    }

    if (version == null) {
        throw new BuildException("version cannot be null.");
    }
}

      

Is there a less sure way to do this? I hate reuse if

like this, and if there is a more efficient way to do it, I'd love to see it. I can imagine what it would look like if I had, say, 20 different variables that I need to check before executing execute ().

What is a good technique for checking a lot of different variables as a continuation of predecessor code, or for displaying a helpful error message?

+3


source to share


3 answers


You can store arguments in HashMap<String, String> argMap

by matching the argument names to their values. Adjust your getters / setters accordingly. Then:



for (String key : argMap.keySet()) {
    if (argMap.get(key) == null) {
        throw new BuildException(key + " cannot be null.");
    }
}

      

+7


source


Small improvement can be achieved with assertions:

public void execute()
throws BuildException
{
    assert server!=null : "server cannot be null";
    assert version!=null : "version cannot be null";
    ...
}

      



... And then run ant always with the -ea

JVM (Enable Asserts) option .

Yes, you still need to encode one variable statement, but at least it will be just one line per one of them.

+1


source


If you'd rather not add a map (as in Claudiu's answer), you can use reflection:

private void checkArgs() throws BuildException, IllegalAccessException {
    for (Field field: this.getClass().getDeclaredFields()) {
         if (field.get(this) == null) {
             throw new BuildException(field.getName() + " cannot be null.");
         }
    }
}

      

but note: getDeclaredFields () will return all fields of the class (private, protected or public).

0


source







All Articles