Reading values from sObjects is just as easy as setting them. We can retrieve the value of a field by using the dot notation along with the API name of an existing field.
Say we had a custom sObject in our org named OrderItem__c
that has the fields Quantity__c
and UnitPrice__c
. The total cost of OrderItem__c
is determined by multiplying these fields.
The method below accepts a single instance of OrderItem__c
as a parameter. It then reads field values from the sObject record and uses it to calculate the total cost.
public Decimal getTotalCost(OrderItem__c orderItem){ Integer quantity = orderItem.Quantity__c; Decimal unitPrice = orderItem.UnitPrice__c; Decimal totalCost = unitPrice * quantity; return totalCost; }
Combine this with setting fields and you got the world on a string, baby!
public void setTotalCost(OrderItem__c orderItem){ Integer quantity = orderItem.Quantity__c; Decimal unitPrice = orderItem.UnitPrice__c; Decimal totalCost = unitPrice * quantity; orderItem.TotalCost__c = totalCost; }
Sometimes these variables can make our code verbose. If you prefer, you could also write the method like this:
public void setTotalCost(OrderItem__c orderItem){ orderItem.TotalCost__c = orderItem.Quantity__c * orderItem.UnitPrice__c; }