Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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.";
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top