Search code examples
javafunctionparameterscoding-style

How to check any two parameters of a function are null


Suppose I have a function that takes three parameters. Of course I could check that any two parameters of this function is null in this way.

returnType function(p1, p2, p3){

  if((p1 == null && p2 == null) || (p2 == null && p3 == null) || (p3== null && p1 == null)){
       return;    
   }

}

But this is rather cumbersome and wouldn't scale for larger number of parameters.

What would be the elegant way to do this?

Thanks in advance.


Solution

  • returnType function(p1, p2, p3){
       Object[] args = {p1, p2, p3};
       if(Collections.frequency(Arrays.asList(args), null) >= 2) {
            return;
       }
    }