A good way to null check a long list of parameters

Suppose for some method I have a long set of parameters for the same type. I have a similar operation for each parameter (if they are not equal to zero). Suppose I have no control over the method signature, since the class implements the interface.

For example .. something simple. A set of string parameters ..

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 to iterate over the list of String parameters to check if they are null and print them out without having to refer to each variable separately?

+6
source share
3 answers

You can just 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); } } 
+12
source

You can write your own method with var args and call it from the methodName function

check(param1, param2, param3)

 static void check (String ... allParams) { for (String param : allParams) { checkNotNull(param); // guava function checkNotNull } } 
+3
source

The shortest I could think of was

 public void methodName(String param1, String param2, String param3, String param4) { if(Arrays.asList(param1, param2, param3, param4).contains(null)) throw new RuntimeException("Supply all params"); } 
+2
source

Source: https://habr.com/ru/post/959409/


All Articles