In this case, the string has to be initialized in order to return it. I always thought that either option (setting it to "" or to null looks kind of ugly. I was just wondering what others do here...or is it more of just a matter of whether you want empty string or null being passed around in your program (and if you are prepared to handle either)?

Also assume that the intermediary logic is too long to cleanly use the conditional (? :) operator.

+3 A:

return (someCondition) ? "something" : "";

or

return (someCondition) ? "something" : null;

Typically though if your function says it will return a String I prefer to actually return a String instead of a null. Either way the calling function should probably check for both cases.

Also, the original poster has altered his question "assume that the intermediary logic is too long to cleanly use the [ternary] operator." He's not asking about using a ternary operator or not, he asking about whether it's best practice to return a null or an empty string.

Yes, this is just a matter of whether you want a null or an empty string being passed around in your program. If you plan to append things to it later, and the someCondition just indicates that you should give it a first value to begin with, then use the empty string. If you plan to have it indicate that there is a string or there is nothing, then perhaps using null is better.

Its just your preference of what your api should do. If you are returning null, there may be a chance that the api users can get NPE if they are not checking for null. But if you are using "" string, the error may pass silently if it is not supposed to be null. It is a preference of how you write your api and depends on the use case.

in general i would return null to signal that nothing was processed,
it might later pop up cases where someCondition is true but the string you build together is "" anyway, that way you can differentiate from that case if you return null if nothing was processed.

It may seem a bit overkill for a boolean condition, but if you get into more complex conditions (more choices, like enums and the like), it would nicely abstract that logic away. And with a descriptive method name make it almost self-documenting to boot.

I'm a bit overconscious about quality. I prefer that all my "if" statements have an "else", because (1) it helps to understand the code if there are multiple nested "if's", (2) force me to consider the possibility (what should happen if the condition is false?).

Regarding reason (1), I prefer to avoid nested if's, but sometimes you inherit code with a lot of if's.

if(someCondition)
aString = "something";
else
aString = "";

I would prefer "null", because it would make the app fail and dump a stack that I can follow. An empty string, in contrast, would keep things going. Naturally, it depends on the logic of your code what is better: null or "".