4

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

4

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.