Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good way to null check a long list of parameters

Tags:

java

methods

Suppose I have a long set of of parameters all of the same type for some method. I have a similar operation to do on each parameter (if they are not null). Assume I have no control over the method signature since the class implements an interface.

For example.. something simple like this. Set of String params..

public void methodName(String param1, String param2, String param3, String param4){

    //Only print parameters which are not null: 

    if (param1 !=null)
        out.print(param1);

    if (param2 !=null)
        out.print(param2);

    if (param3 !=null)
        out.print(param3);

    if (param4 !=null)
        out.print(param4);
}

Is there any way I can iterate through the list of String parameters to check if they are not null and print them without having to reference each variable separately?

like image 484
Carl Karawani Avatar asked Dec 05 '13 17:12

Carl Karawani


1 Answers

You can simply do

for (String s : Arrays.asList(param1, param2, param3, param4)) {
    if (s != null) {
        out.print(s);
    }
}

or

for (String s : new String[] {param1, param2, param3, param4}) {
    if (s != null) {
        out.print(s);
    }
}
like image 63
JB Nizet Avatar answered Sep 19 '22 23:09

JB Nizet