11

I often do '' + field where field is an SObjectField to get the field's API name. I like that much more than the clunky verbose field.getDescribe().getName().

So is there a reason I should not do it using the toString() method? Will Salesforce change the output eventually?

1
  • 2
    Type coercion is not at all the same as calling toString. You do have issues around null-safety potentially, depending on where the input is coming from.
    – Adrian Larson
    Commented Jan 24, 2019 at 19:09

1 Answer 1

9

So is there a reason I should not do it using the toString() method?

String concatenation isn't strictly the same as toString() in Apex. For one thing, many things that should have a toString() do not actually have one, but instead have to be evaluated through String.valueOf(Object param) instead.

This is a marked difference compared to Java, where Object, the parent of all other objects, has a functional toString() of its own. One example of this I found was through String.join, which logically sounds like it should use toString() where available, but doesn't, leading to some surprising output.

class demo {
    public override string toString() {
        return 'Hello';
    }
}
System.debug(
    String.join(new demo[] { new demo() }, '')
);

Output:

USER_DEBUG [6]|DEBUG|anon$demo

Using string concatenation reduces CPU and heap usage by a minuscule amount, though it could add up in large loops. The only difference real difference between the two is one would give you a string 'null' (concatenation) while the other would throw a NullPointerException (by reference).

If there's one thing I'd call a drawback is that using string concatenation dynamically with null values could lead to spurious errors elsewhere in your code, such as 'invalid field null in query' or something. At least with a NullPointerException, you already immediately know which line was the cause instead of some bizarre error down the line.

Will Salesforce change the output eventually?

Salesforce couldn't easily change this behavior, because it is very widespread in usage. At best, they could only make a versioned change (e.g. it behaves differently in a hypothetical version 99.0 versus 98.0), otherwise it could cause all sorts of havoc. It's easier to just let the behavior stay the way it is.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .