Home » Blog » Simplify Your Apex Code With This “Empty” Utility

Simplify Your Apex Code With This “Empty” Utility

Sometimes the initialization of or assignment to String and List variables in Apex can be confusing. Here’s a quick quiz for you. Which assertions below will fail (assuming that a failed assertion doesn’t stop execution)?

public class AddressController {
  //--------------------------------------------------------------------------
  // Properties
  public String street { get; set; }
  public String zipCode;

  //--------------------------------------------------------------------------
  // Constructor
  public AddressController() {
    System.assertEquals(null, street);
    System.assertEquals('', street);

    System.assertEquals(null, zipCode);
    System.assertEquals('', zipCode);

    Account[] accounts = [SELECT Id FROM Account WHERE Name = 'bogus'];
    System.assertEquals(null, accounts);
    System.assertEquals(new Account[] {}, accounts);
  }
}

Now what if street is bound to an input control on a Visualforce page and submitted without anything being entered. Will it be null or ?

It’s easy to create countless bugs related to this issue. Keeping all the rules straight is challenging. Eventually, you may have statements like the one below all over the place:

if ((null != street) && (0 != street.trim().length()) &&
  (null != accounts) && !accounts.isEmpty()) {
  ...
}

And instead, write this:

if (!FC.nullOrEmpty(street) && !SF.nullOrEmpty(accounts)) {
  ...
}

Here’s a little utility function that saves time and makes the code more readable – nullOrEmpty():

/**
 * @description utility method for determining if an object is null or blank.
 * For strings, 'blank' means empty or only whitespace. A 'blank' List has
 * no elements.
 *
 * WARNING this method doesn't work with sets or maps
 *
 * @param o the object to test 
 * @return true if the specified object is null, empty, or only whitespace
 */
public static Boolean nullOrEmpty(Object o) {
  return (null == o) ||
    ((o instanceof String) && (0 == ((String)o).trim().length())) ||
    ((o instanceof List<>) && (0 == ((List<object>)o).size()));
}

P.S. We’d love to learn how to make this work with Sets and Maps. Somehow, Set is not recognized as an instanceof Set and Map<String,String> is not recognized as an instanceof Map<Object,Object>. Please comment below if you’ve got ideas.