Best way to check if return string is null in Java

I have a function that combines a set of lines like this:

StringBuffer sb = new StringBuffer();

sb.append(fct1());
sb.append(fct2());
sb.append(fct3());

Where fct1 (), fct2 () and fct3 () should return String. The problem is that I have to check the return values ​​as follows:

sb.append(fct1() == null ? "" : fct1());

because I get an exception if the value is null.

The problem is that I have a lot of instructions like this, and above all, I cannot change these functions that return strings (fct1, fct2 and fct3).

Is there a solution that will automatically "clear" my lines?

Thank.

PS: I created a function that can do this:

public String testNullity(String aString){
aString == null ? "" : aString;
}

so that I can call it like this:

sb.append(testNullity(fct1));
sb.append(testNullity(fct2));
...
+3
source share
6 answers

Another alternative could be

 public class SafeStringBuilder  {
    private StringBuilder builder = new StringBuilder();

    public SafeStringBuilder append(String s) {
        if (s != null) 
            builder.append(s);
        return this;
    }
 }
+4

, Guava Joiner StringBuffer:

Joiner j = Joiner.on("").skipNulls();
StringBuilder sb = new StringBuilder();
j.appendTo(sb, fct1());
j.appendTo(sb, fct2());
j.appendTo(sb, fct3());
String result = sb.toString();

// or even just
Joiner j = Joiner.on("").skipNulls();
String result = j.join(fct1(), fct2(), fct3());

N.B. , StringBuffer , StringBuilder. API, .

+1

, , , . (, , - , .)

0

, testNullity() - , Java ( ). , : StringUtils.html#defaultString.

0

StringBuffer:

class MyStringBuffer {
    StringBuffer _sb = new StringBuffer();
    public boolean append(String s) {
        _sb.append(s==null ? "" : s);
        return s == null;
    }
    public String toString() { return _sb.toString(); }
}
0

API , ( ) .

, System.getProperty() , , , null, . , fct* " ", .

, # ??, , ( sb.append(fct2() ?? "")), , Java .

:

public void appendIfNotNull(StringBuffer sb, String s) {
    if(s != null) {
       sb.append(s);
    }
}

append , , .

0

All Articles