2

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?

11
  • It's not clear what you're trying to achieve, or where the validation is currently occurring. Commented Aug 30, 2012 at 18:32
  • 1
    the function fails before anything is executed because the NULL type doesn't match java.lang.String. So I never even make it inside the function Commented Aug 30, 2012 at 18:33
  • 1
    @vasek1: That should not fail. See this example. Can you please show us the exact code that gives the error? Commented Aug 30, 2012 at 18:38
  • 3
    @vasek1: That should be fine. Please show a short but complete program which demonstrates the problem. Commented Aug 30, 2012 at 18:38
  • 1
    what is Wap in "Wap:java.lang.String" ? Commented Aug 31, 2012 at 10:10

3 Answers 3

1

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..

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.