문제

I'm concerned about this construct:

String out = "Text " + (obj==null ? "" : obj.getStr()+" ") + "text continues.";

It works and all, but I think it's ugly. Maybe I'm just too picky..

Anyway, I'm asking, is there some nicer way to do this kind of stuff?
Or is this the generally accepted technique?

도움이 되었습니까?

해결책

Use a StringBuilder:

final StringBuilder sb = new StringBuilder("Text ");
if (obj != null)
    sb.append(obj.getStr()).append(' ');
final String out = sb.append("text continues.").toString();

Also, why .getStr()? Doesn't obj implement .toString()?


Note that if obj did implement .toString(), you could do "better" than that using Guava's Joiner:

private static final Joiner JOINER = Joiner.on(" ").skipNulls();

//

final String out = JOINER.join("Text", obj, "text continues.");

Ultimately, though, that is a question of style.

다른 팁

Well you can separate out the logic from the format, to start with:

String out = String.format("Text %stextcontinues",
                           obj == null ? "" : obj.getStr() + " ");

I like it better because it is concise.

The other way is the plain old if-then-else:

String toAdd = "";
if(object != null) {
    obj.getStr() + " ";
}
String out = "Text " + toAdd  + "text continues.";
String out = "Text text continues.";
if (obj != null)
   out = "Text " + obj.getStr() + " text continues.";
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top