5

This question is not about how to solve the problem but rather why it is there in the first place.

So consider these four lines:

Object myString;
Object myDecimal;

System.debug(String.valueOf(myString));
System.debug(Decimal.valueOf((String) myDecimal));

The first statement will work but the second statement will not and I'm really wondering why? I mean - converting a null value to a different type shouldn't be a problem, right? It's still null after all.

Of course I could easily fix this by having a null check in place:

myDecimal == null ? myDecimal : Decimal.valueOf(myDecimal);

While this will work - I would have to add this to every valueOf with a null input would also yield a bulk output.

Any ideas?

See also: Date.ValueOf not accepting null

1 Answer 1

6

It's a design choice:

  • The author of the String.valueOf chose to allow a null argument (presumably generating the string 'null').
  • The author of Decimal.valueOf chose to report a null argument as an error; I would guess the thinking there was better to "fail fast" rather than propagate the null.

To avoid lots of null checks, design your code to avoid null values by e.g. initializing variables where they are declared. If a value of null has to be allowed, address that in one place only by e.g. not calling other code that requires a non-null value.

See e.g. 10 Tips to Handle Null Effectively; a couple of these are specific to Java but most apply to Apex.

2
  • 1
    The problem is, Null can be returned by SOQL, even if you know that the field type is Decimal. Because of this, you need to write unnecessary checks in all these places… like this: if (a.Length_Of_Service__c == Null || a.Length_Of_Service__c == 0)
    – pilat
    Commented Jun 24, 2022 at 11:29
  • After coming back to this after some years I just wanted to point out that String.valueOf does not generate the string 'null' but rather just returns the null-string that was passed. This also fails for integers and I guess other types as well - seems like string is the only one that returns null.
    – Semmel
    Commented Oct 19, 2023 at 3:52

You must log in to answer this question.

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