3.3 Use methods that takes parameters

The concept

In our previous post ,  we mentioned that variables can only store values. It doesn’t remember the formula. Remembering formula can be achieved via functions. Now let’s do it. We create a new class in our developer console called Commodity.

public class Commodity 
    public Decimal price;
    public Decimal retrieveSalesTax(Decimal taxRate) 
        return price * taxRate;
    public Decimal retrieveTotalPrice(Decimal taxRate, Decimal additionalFee)
        return price + retrieveSalesTax(taxRate) + additionalFee;

Then in your anonymous block:

Commodity c = new Commodity();
c.price = 90;
System.debug(c.retrieveTotalPrice(0.09, 0));

c.price = 200;
System.debug(c.retrieveTotalPrice(0.11, 10));

Execute it. Your result should look similar to this:


A bit explanation

In this section, I have showed you how to pass variables to methods.

So in the parenthesis () of the function declaration, we can have a list of parameters. We can have as many parameters as you want. The grammar is a list of parameters separated by comma. All the parameters have a type and a variable name.

Please note the parameter can only be used within the function.


In our previous post’s exercise, we have defined a Person class. Define a function to calculate this person’s income tax, and try calling that function.

Next Post

3.4 Pass by value and pass by reference

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *