[SalesForce] SObject Numeric field – Integer.valueOf() vs casting

When working in Apex it is not uncommon for us to work with a numeric field that has a 0 scale. To use that with some built in functions we need to use an Integer. To provide an example, let's say we have a field on Account TrainingDays__c. This field always holds a whole number.

To use this field with Date.addDays() we need to convert the Decimal value that acct.TrainingDays__c is represented in to an Integer. For this task we have two options: Integer.valueOf(acct.TrainingDays__c) or (Integer)acct.TrainingDays__c.

I know that there are some differences when working in other languages, but for the given example where the source value is a numeric SObject field:

  • Is there ever a time when one of the methods would throw an exception and the other would not?
  • Is one more performant than the other?
  • Other than code consistency is there any reason to standardize on one approach?

Best Answer

For your specific example, there is this third way:

Integer i = acct.TrainingDays__c?.intValue();

or:

Integer i = acct.TrainingDays__c?.round();

The benefit of using these methods is that they more clearly express what is being done and provide options in how the operation is done (e.g. rounding mode).

Methods like Integer.valueOf make sense when you don't know the type of the argument.

As for using casting for this particular conversion, I'm a little surprised it even works. That observation leads to a reason you haven't included in your list: the most important reason to choose is clarity for someone reading the code (e.g. someone other than you changing the code in 2 years time). Whether the operation takes 1 microsocond or 10 microsoconds is irrelevant if a a 5 millisecond query comes soon after. See e.g. we should forget about small efficiencies, say about 97% of the time.

+1 for sfdcfox's measuring to get the performance figures rather than speculating.