vasek1
vasek1

Reputation: 14071

java: how to handle null in several function parameters at once?

I have a function which takes in three strings, and any of them or all three might be null (not known in advance). What is the best way to handle this?

The base case is this:

public String doStuff(String a, String b, String c) {
  //do stuff
}

If this is called with nulls in any of the strings, I get this error:

-> doStuff("test", null, null)

Unable to execute method public java.lang.String
doStuff(java.lang.String,java.lang.String,java.lang.String)  
on object 1c52ac68 of class test with arguments {Wap:java.lang.String, null, null} of size 3

I guess I could overload this for all the possible permutations of nulls in the three inputs, but is there a better way?

Upvotes: 2

Views: 128

Answers (3)

LeeNeverGup
LeeNeverGup

Reputation: 1114

You can write like that:

int nulls=0;
if(a==null) nulls+=1;
if(b==null) nulls+=2;
if(c==null) nulls+=4;

and then switch nulls:

switch(nulls){
  case 0://no String is null  
    ...  
    break;  
  case 1://just a is null  
    ...  
    break;
  case 5://(5=101b), a and c is null
    ...
    ...
}

and so on.

Upvotes: 1

KD.
KD.

Reputation: 2055

Not sure whats the end result you want. If you say your doStuff just do a string concat and you don't need a null in that then do this..

doStuff(String a, String b, String c){
        String x = "";
        if(null!=a) x = x+a;
        if(null!=b) x =x+b;
        if(null!=c) x = x+c;
        System.out.println(x);
}

Upvotes: 0

stephen.hanson
stephen.hanson

Reputation: 9604

I don't know how to get around your issue, but if you're just trying to make it easier to check, you could make a utility function to check if any of the parameters is null:

public boolean verifyNotNull(Object.. objects) {
    for(Object o : objects) {
        if(o==null) return false;
    }
    return true;
}

Then you could call this utility in your function:

public String doStuff(String a, String b, String c) {
    if(!verifyNotNull(a,b,c)) {
        throw new MyException("...");
    }
}

Maybe AOP could do something for you too..

Upvotes: 1

Related Questions