Cooking with Code: Yummy Apex Utility Classes

Apex Utility ClassesWelcome back to Cooking with Code. Today we are going to take a deeper dive into the ins and outs of apex classes.

We looked at this in my intro to Object Oriented Programming (OOP) post, but today we’re going to go over what are commonly called Utility Classes. I know, right?! Who doesn’t love a little utility in their lives?

Utility classes are primarily used as places for code that performs a bunch of actions, rather than creating objects.  They are super helpful in Apex.

What is a Class?

Before we go into what a utility class is, let’s remind ourselves what a class actually is.

Most code within any OOP language is organized into classes. Classes are files that store your coded business logic and are triggered when you do something in your database (e.g., create or save a record, delete something, etc.).  In the case of Salesforce, where all things are cloud, they are stored in your salesforce org.

You can see all the classes you have in your org by going to:

Setup > Build > Develop > Apex Classes

Anatomy of Apex Utility Classes

So first things first, let’s break down the basic anatomy of a class.Change is made to a database record. The trigger hears the change and fires off the apex class. The apex class contains variables and methods that do things with the data. Variables are containers that hold data (singular or as collections). Methods are code that do stuff.

Classes contain attributes (or variables) and methods.

  • Attributes store values or collections of values
  • Methods do stuff

Below is probably the most basic class you could ever write. Not exciting … it doesn’t really do anything … but it is a perfectly legitimate piece of code.

public class RecipeUtil {
    // this is the body of the class
}

What we’re doing here is creating a class called “RecipeUtil” (class names must be unique to the Salesforce Org) and saying that it is “public.” The public piece is called an access modifier, and it basically sets some security around where the class can be called (e.g., what code can run it).

We’ll get into access modifiers a little later on.

Then there is a code block between two curly braces “{}”.

More on Methods

Let’s build on this with some method code:

public class RecipeUtil {
    public static void createReviews (List<recipe__c> listOfRecipes){
        //code that creates reviews
    }
}

With the code above, we have basically added a public static method (again, we’ll talk about access modifiers and static vs non-static later), called “createReview,” which accepts in a list of recipes and, from the name, you can assume that eventually it will create a review for each recipe.

We need to call this list of recipes something when we’re using it within the method, so in this case we’ve called in “listOfRecipes” (seems appropriate).

To Return or Not to Return

You might be wondering what the “void” piece is all about.

When you create a method, you must tell Salesforce whether you expect it to return a value, or state that it will NOT return anything.

Our method is using void because we aren’t going to return anything back to the code that called the method.

We could return something (like the ID of the Reviews being created), but in this case we aren’t going to need to use that, so we’re just going to say void and be done. Note that you can either choose void or a single data type (which could be a collection, i.e., a list, map or set).

If you did want to return something, the code could look like this:

public static id createReviews(List<Contact> listOfRecipes){
    //code that creates the review,
    //which will include returning an ID for the recipe created.
}

Where “ID” is the datatype of the attribute being returned. If instead you wanted to return the due date for the review, the code would look like this:

public static date createReviews(List<Contact> listOfRecipes){
    //code that creates the review,
    //which will include returning the due date for the review created.
}

See that “id” is now “date.” Again, we have not added any code that actually creates the review, but this gives you an idea of the basic structure of the method.

Parameter vs Argument

Note: Only read this section if you are like me, and love words and grammar and the pickiness of language.

You may have noticed that at different times I’ve use the words, “attributes”, “variables”,  “parameter” and other times “argument.” There are actually technical difference between all of these words. Let’s check it out!

  • Attribute is the parent name for all the terms below
    • Variables are attributes whose value may change
    • Constants are attributes whose value can’t change.
    • Parameters and Arguments relate to methods:
      • Parameters are the attributes that you feed into the hungry method.
      • Arguments are what these attributes are called when they are being used within the method.

At the end of the day, unless you are interviewing for a programming job, you probably don’t care. But at least now you know!

The hungry, hungry method

So the data that you feed your method is called a parameter, and unlike the return value, you can pass in as many parameters into a method as you want.

All you need to do is separate the datatype and what you want to call the attribute locally (e.g., within the method) with commas.

So for example, imagine we wanted to pass the following into our method:

  • List of recipes (called “listOfRecipes” within the method)
  • A string variable for status level (called “statusLevel” within the method)
  • An integer variable for priority (perhaps used to assign due dates) (called “priority” within the method)

Then our code could look like this:

public class RecipeUtil {
    public static void createReviews(List<recipe__c> listOfRecipes, string statusLevel, integer priority){
        //code that creates reviews
    }
}

You may now have some more questions, like:

  • Where are these values coming from?
  • How does the method know which one is assigned to what data type?
  • What happens if you don’t pass a variable and the method is expecting it?

Those are all really GREAT questions! (Well done you!)

Where are these values coming from ?

They come from whatever code is calling the method. So a very common source is a trigger calling a method within the class and passing it parameters. Another common source is another method, either from within the same class, or from another separate class.

How does the method know which parameter to use where?

Parameters must be passed into the method in the same order that they are specified in the receiving method. So for example, in the code above, we would get an error if we tried to pass parameters in anything but the following order:

  • List
  • String
  • Integer

So the code in this case might look something like:

public class RecipeUtil {
    public static void updateRecipe (list<recipe__c> listOfRecipes){
        //code that runs some kind of code to update recipes.
        //code that then calls the createReviewsmethod
        RecipeUtil.createReview(listOfRecipes,'open', 1);
}

    public static void createReviews(List<recipe__c> listOfRecipes, string statusLevel, integer priority){
        //code that creates reviews
    }
}

Line 5 is calling the method on line 8, and passing in three parameters, a list, a string, and an integer.

But why would you do this, when instead you could just lump all the code together, and update the recipe and create the reviews in one method?

Well, you’re right, could do that, but what if you wanted to do some kind of complex validation to only create a new review when a set of criteria was true about an individual recipe. Then we would only want to list the createReviews code some of the time.

Keep in mind that more atomic code is easier to read, understand, debug, and test. So you should generally separate out any complicated business logic into a separate methods, and then call that method only when you need it.

So you would put all that criteria in one separate method, create a new list of just the recipes that you wanted to create reviews for, and pass that list parameter to the createReviews method.

That code could look something like this:

public class RecipeUtil {
    public static void updateRecipe (list<recipe__c> listOfRecipes){
        //create an empty list to collect all the recipes that we
        //want to create reviews for. Note that it is "private" –
        //we'll talk about that in a sec
        private list<recipe__c> listOfRecipesToCreateReviewFor = new list<recipe__c>;

        //loop through the listOfRecipes
        //perform some kind of check to decide which recipes should get reviews
        //add these recipes to the listOfRecipesToCreateReviewFor list
        //code that then calls the createReviews method
        RecipeUtil.createReview(listOfRecipesToCreateReviewFor,'open', 1);
    }

    public static void createReviews(List<recipe__c> listOfUpdatedRecipes, string statusLevel, integer priority){
        //code that creates reviews using the listOfRecipesToCreateReviewFor
        //that was passed into the listOfUpdatedRecipes list
    }
}

What happens if you don’t pass a parameter and the method is expecting it?

You will get a lovely error if you try to call a method and either:

  • You don’t have the correct number of parameters
  • The order of data types passed in don’t match the order of datatypes that the method is expecting.

Static vs Non Static Methods

So what’s up with that “Static” keyword? What does that do?

Static simplifies code because it means that you don’t need to instantiate an object before using it. You simply call out the class and method using dot notation:

  • RecipeUtil.createReview()

Static is used a lot with utility classes, because most of the time you don’t want or need to create instances of the object … you just want to do whatever your method is coded to do.

That is a gross simplification…there is waaaaay more to it than what I’m saying, but for now, just think of “static” as one of the cool things you can do within utility classes to save you some coding time and move on.

Access Modifiers

So let’s deal with this whole public/private keyword thing. You might have noticed in the code sample that classes, methods, AND variables all have access modifiers.

Access Modifiers help define the scope of the thing that they’re modifying, and they are all about making your application secure.

So for example, if we have a “public” method, then that means that any code in your salesforce org can access that method. But you don’t always want that (it’s not a very secure way to code). Likely we can say that a method is “private.”

The two most common access modifiers are “public” (available outside the class anywhere in your Salesforce org) and “private” (only available within the class).  There is a third, “global“, that you’ll see if you want your code to be available outside of your Salesforce org (e.g., as a web service).

By default, if you don’t specify anything, your class, method, or variable will be private.

Most of the time you’ll want your classes to be public (because otherwise they can’t be used), but you can choose whether you want your methods and/or attributes to be public or private.

This is just the high level overview … there is a ton more we can learn about access modifiers, but that’s a topic for another post.

Summing Up…

Today we learned about the yummy world of utility classes where you found that not all classes exist to create objects. Some just are super useful as places to hold code that doesn’t need an object to run (which actually is most of the classes you will need).

Apex Utility ClassesYou also learned that:

  • Classes have attributes that store values.
  • Classes have methods that do stuff.
  • Classes, methods and attributes have access modifiers that control where they can be used.
    • Classes are generally public.
    • Methods and attributes can be public, private or global
      • Private: only available in the class (for methods) or method (for attributes). If you don’t specify anything this is the default.
      • Public: available throughout the Salesforce org
      • Global: available outside of the Salesforce org (e.g., a web service)
    • Methods either return a single data type, or need to be specified as returning “void” (which means they don’t return anything)
    • Static methods are cool, because they don’t have to be instantiate a class to use them. You can just point to them using the <classname>.<methodname>(<parameters>).
    • You can feed your hungry method with parameters:
      • You can pass no, one, or many parameters
      • Parameters must be passed in the same order that they are defined in the target method.
      • Extra Credit: You pass parameters into a method, and you use arguments within them.

Phew! That was a LOT. I hope this satisfied your coding hunger … or perhaps it’s just stimulated your app-building appetite! I don’t know about you, but I think I may need to go raid the coding fridge.

Looking forward to seeing you in the coding kitchen!