RSS

Category Archives: Apex

Proper Case and Title Case Methods for Apex

Proper Case and Title Case Methods for Apex

Apex doesn’t have a built-in proper case or title case method. Apparently this isn’t something that is in too high of a demand–on the idea exchange there are only 26 votes for a properCase or titleCase method to be added to the String class (https://success.salesforce.com/ideaView?id=08730000000Do1xAAC).

This sort of bums me out because I love having a database that is all clean and pretty without any SHOUTING or whispering (all lowercase when capitalization is more appropriate).

So I guess it’s time to get to work and write a couple of my own methods:

  • toProperCase
  • toTitleCase

Method 1 – toProperCase

Prim and proper lady

This method is the one I’ll use most often. It’s designed to handle phrases that do not have peoples’ names.

After writing my first draft I found a nice little method posted on the Salesforce Developer forum (https://developer.salesforce.com/forums?id=906F00000008ukJIAQ) that had a really cool idea to store words typically kept lowercase in a set, and to always capitalize the first and last words (my first version just capitalized every word no matter what).

Here is the resulting code:

/**
 * @TO_PROPER_CASE
 * turns all words in a text string to proper case except those that should be kept lower case
 * first and last words are always capitalized
 * Example: "sally sue sews shirts" --> "Sally Sue Sews Shirts"
 * this method does not handle parts of names that are kept lowercase of have a capitalized character within the name
 *
 *String str = toProperCase(str);
 */
public static String toProperCase(String str){
   if(str.trim().length() == 0) return str;
   Set lcaseWords = new Set{'a','an','and','at','but','for','in','nor','of','or','the','to','with'};
   String[] words = str.toLowerCase().normalizeSpace().split(' ');
   String rslt = words[0].capitalize(); //always capitalize the first word
   for(integer i=1; i<words.size()-1; i++){
      if(lcaseWords.contains(words[i])) rslt += ' ' + words[i];
      else rslt += ' ' + words[i].capitalize();
   }
   rslt += ' ' + words[words.size()-1].capitalize(); //always capitalize the last word
   return rslt;
} //end method toProperCase

Method 2 – toTitleCase

title case

This method had a few additional little words that are typically kept lowercase in a person’s name – things like van, von, de, and la. It also attempts to accommodate Mc, Mac, Van, and Von prefixes.

/**
 * @TO_TITLE_CASE
 * turns all words in a text string to proper case except those that should be kept lower case
 * first and last words are always capitalized
 * Example: "sally van ferstenclass" --> "Sally van Ferstenclass"
 * this method handles parts of names that are kept lowercase of have a capitalized character within the name
 *
 *String str = toTitleCase(str);
 */
public static String toTitleCase(String str){
   if(str.trim().length() == 0) return str;
   Set lcaseWords = new Set{'a','an','and','at','but','for','in','nor','of','or','the','to','with','de','la','the','van','von'};
   String[] words = str.toLowerCase().normalizeSpace().split(' ');
   String rslt = '';
   for(integer i=0; i 2 && str.startsWith('mc')) rslt += ' Mc' + str.right(str.length()-2).capitalize();
      else if(str.length() > 3 && str.startsWith('mac')) rslt += ' Mac' + str.right(str.length()-3).capitalize();
      else if(str.length() > 3 && str.startsWith('van')) rslt += ' Van' + str.right(str.length()-3).capitalize();
      else if(str.length() > 3 && str.startsWith('von')) rslt += ' Von' + str.right(str.length()-3).capitalize();
      else if(lcaseWords.contains(words[i])) rslt += ' ' + words[i];
      else rslt += ' ' + words[i].capitalize();
   }
   return rslt.trim();
} //end method toTitleCase

 


So there you have it. Not earth shattering, but possibly useful.

Cheers!

Advertisements
 
Leave a comment

Posted by on February 2, 2018 in Apex, Utility Methods

 

Tags: ,

Apex Tidbits

Apex Tidbits

Here is a collection of little tidbits I’m noticing while learning Apex. I’ve just started this post, so there’s not much here yet, but I’ll add to it as I can.

 


list view

Declaring and Instantiating List Variables and Bracket Notation

There are two ways to declare a List variable:

  1. List<Account> acctList;
  2. Account[] acctList;

I happen to love the bracket notation. Just two little keystrokes and you’re done (as opposed to an extra four with “List<>” notation).

But as I was hobbling along it seemed that brackets were supremely frowned upon used to the right of the variable name when instantiating a new list: acctList = new Account[]; gives the compiler fits!

No Good

So up until now I’ve been forced to use all those extra key strokes: acctList = new List<Account>();

eye roll

But I have happily just learned from the profoundly Salesforce-savvy, Doug Ayers, that there is some hope for the brackets to the right of the variable after all!

Here are some of the ways listed in this article, Apex Code: The Basics, that had previously escaped my searches on how brackets can be used:

Account[] accs2 = new Account[]{};
Account[] accs3 = new Account[]{new Account()};
Account[] accs4 = new Account[4];
Integer[] ints2 = new int[]{1, 2, 3};
Integer[] ints3 = new int[6];

See all those lovely brackets to the right of the variable? I’m doing my happy dance right now!

snoopy happy dance

The trick to finding this cool info, it seems, is to know that Lists and Arrays are the same thing with only one slight difference note: an Array is a one-dimensional List only, whereas a List can be one- or multi-dimensional:

String[] stringArr == List<String> stringArr  <– these are 1-dim arrays

List<List<String>>  <– this is a 2-dim list for which there isn’t an equivalent bracket (array) notation.

I think I’ll write a little more about this later.

 


Compound Address Fields – Can They Be Passed Into a Method?

compound address field

It’s pretty nifty that all the address fields on standard objects can be accessed in SOQL with a single word: ShippingAddress, MailingAddress, etc. I ran across a situation, however, that has completely stumped me, and after six hours of monkeying around trying various solutions I finally threw in the towel.

Here is what happened:

I wrote a little utility to see if two addresses were the same (this is the bare-bones…it needs to check for null variables to be more robust):

isSameAddress Method

The idea was that it would examine the latitude and longitude of the address fields and let the calling routine know if they matched or not.

It worked in my test routine just fine:

isSameAddressTest Method

But I couldn’t get it to work in a Trigger no matter how hard I tried and what I tweaked. Over and over again the dreaded FATAL_ERROR – Attempt to de-reference a null object.

Fatal Error

I even assigned the field to a System.Address variable and tested it with the same result.

System.debug(addressVar == null) and System.debug(acct.ShippingAddress == null) always yielded true, even when the address was fully populated.

That leaves me wondering, do compound address fields in a Trigger record always equate to null?

There must be a trick here, it just hasn’t posed itself to me just yet.

cup and ball trick

So to work around the problem I had to skip using my handy-dandy utility method and test for same addresses in the Trigger helper class itself:

Inline Address Test

This is a head scratcher and I’d really like to know what is going on, so if you know, enlighten me please!!


More soon…

 
2 Comments

Posted by on February 1, 2018 in Apex

 

Tags:

Interfaces, Extensions, Abstractions, & Virtual Classes

Interfaces, Extensions, Abstractions, & Virtual Classes

I’m working on a project that has landed me on a foreign planet in a galaxy far far away where I need to learn about Interfaces, Extensions, Abstract, and Virtual classes. I figured that since I tend to understand something a lot more clearly when I have to write about it in a way that someone else may also understand I might as well generate a blog post!


Interfaces

thWH0B31KN

An interface is a point where two things (systems, subjects, organizations, etc.) meet and interact, like the touch pad on your microwave, the snooze button on your alarm clock, or the computer screen in your intergalactic spaceship.

In Apex a class interacts with the outside world through its methods: the methods form the class’s interface.

As it turn out, you can also define what methods must exist in the class (the class’s interface) with a separate piece of code called an Interface.

So you can think of an Interface as sort of a template for a class. You could also think of it as a Contract where the class that implements the Interface agrees to do something with each of the methods it defines (according to Wikipedia, an Interface is “an abstract type that is used to specify a behavior that classes must implement“).


Here are some points about Interfaces:

Interface

  • An Interface is like a class
    • For example, when you want to write an Interface using MavensMate you tell it that you want to write a New Apex Class
  • Interfaces do not have an access modifier (private, public, protected, or global)
    • By definition Interfaces are always global
  • Another class Implements an Interface
    • Example: public class TriggerDispatcher implements ITriggerDispatcher
    • Multiple Interfaces can be implemented by a single class
  • Methods defined in the Interface are do not have a code body in the Interface
    • Only the method signatures are present followed by a semicolon
    • Method bodies are empty so they’re simply not even written (no curly braces)
      • Example: public String createString(Integer int);   << see, no {} code body, just a semi-colon
  • The class that implements the Interface must provide bodies for each of its methods (although the bodies can be empty)
  • Classes implementing Interfaces can have additional methods from the ones defined in the Interface
  • Multiple Interfaces can be implemented by a single class
  • Many programmers name their Interface classes with an “I” at the beginning
    • Example: ITriggerHandler
  • Interfaces cannot have member variables
  • Interfaces do not have access modifiers like public, private, etc
  • When an Interface extends another interface, the parent interface and methods do not need to be defined as virtual (read on for more on Extending and Virtual)

What are Interfaces Good For?

Interfaces separate the declaration of methods from the implementation of them. This is known as a “level of abstraction” and allows you to have different actions that can occur for the same method.

Here’s an example from the project that is making me learn this stuff: setting up a Trigger Framework.

framework

No matter what object has initiated the trigger, or what type of action initiated the trigger (insert, update, delete, undelete), there will always be a method that each trigger handler will use to initiate its actions. Since it is expected that there will be multiple trigger handlers needed, having them implement an Interface ensures that each will have the same method(s).  In this example the methods of the interface are named “mainEntry,” “inProgressEntry,” and “updateObjects:”

ITriggerHandler

Even though each class that implements the Interface will have a mainEntry method, that method for classes that handle the Account object will have different actions than the one for classes that handle the Asset object. And isn’t it nice when they all have the same method signature? It’s so neat and tidy and makes for such nice, consistent code. 😛

Now classes that implement this Interface must provide bodies for all methods in it. Here is an example where they all have exceptionally skinny bodies:

implementation

skeleton


Interface Data Types

When you define an Interface you are also defining a data type. This means that you can use the Interface name anywhere you would use a data type, like when declaring a variable:

DataType

When you do this you must be sure that any object that you assign to that variable is an instance of a class that has implemented the Interface. In other words, your variable is an Interface type, and all classes that implement the Interface are also Interface types.


Extensions

extensions

An Extension is when one class Extends another class, adding additional or different functionality from what existed in the first class. The extending class inherits all the methods and properties of the first class and then has the ability to add more stuff, too. It’s just like a hair extension which adds to the hair on your head!

The actual terminology is “parent class” for the original class, and “subclass” for the class that extends the parent. Sort of boring. I like “super class” for the new-and-improved version… and maybe “underdog class” for the original. 😀

Classes that extend other classes may also inherit another power: the ability to override methods from the original class. What this means is that the super class may not have to put up with the functionality that came with the methods it inherited, and, instead, can have it’s very own unique functionality for them.

There is a term for this–Polymorphism–which means that classes that extend other classes (subclasses) can have their own unique behaviors yet share some of the same behaviors as the class they extended (the parent class).

In order for this to happen the parent class must be a Virtual class and the methods that can be overridden must be Virtual methods or the parent class must be an Abstract class and the methods that can be overridden must be Virtual methods or Abstract methods. More on this below.


Some Key Points About Extensions

  • A class can extend only one other class
    • (As opposed to Interfaces where a class can implement several Interfaces)
  • The syntax looks like this:
    • Parent Class Definition: public class ParentClass {}
    • Subclass Definition: public class SubClass extends ParentClass {}
  • Interfaces can extend other interfaces
  • In order for a parent class to be extended it must be declared as Virtual or Abstract (more on this below)
  • Subclasses can override virtual methods within virtual classes (polymorphism)
  • Subclasses must override abstract methods within abstract classes if they are going to use them
    • Subclasses can override virtual methods within abstract classes if they want to, but they don’t have to

Virtual Keyword for Classes and Methods

thXFALVMWZ

Virtual is a keyword that is used to modify the definition of a class or method (the technical term is “definition modifier”).

What it means when it’s used in a class definition is that the class can be extended and any virtual methods within the class can be overridden. (Overridden means that you have written your own code that replaces the code in the original method.)

What it means when it’s used in a method signature is that the method can be overridden (as long as that method resides in a class that can be extended).

To override a virtual method all you need to do is re-write the signature of the method and include the keyword “override” right after the access modifier like this:

public override void methodName() {}

holodeck

Some Key Points on the Virtual Definition Modifier:

  • Classes declared to be Virtual can be extended and will allow overrides of their methods that can be overridden
  • Methods within a Virtual class that also have the Virtual definition modifier may be overridden
    • Methods not marked Virtual cannot be overridden
  • Virtual methods must have a code body, but the code body can be empty
    • (As opposed to Interface and Abstract methods which cannot have a code body in the Interface of class where they’re originally defined)
    • Example: public virtual void methodName() {}  << see, a {} code body
  • Interfaces are, be definition, already considered to be virtual so including that keyword in the Interface declaration is redundant (and, in fact, the Developer Console will not allow you to include it)

 Abstract Keyword for Classes and Methods

abstract

Abstract is a keyword that is also used to modify the definition of a class or method.

When used in a class definition what it means is that the class is sort of just floating around in space and cannot be used as-is. It’s “abstract” as in “not concrete.” Since it cannot be used on its own it cannot be instantiated (it isn’t concrete so it can’t really exist).

concrete

It also means that the class may contain Abstract methods.

An abstract method looks almost exactly like a method in a Interface in that it has its signature but no body. The only difference is the signature will also have the “abstract” definition modifier:

  • Abstract method signature: abstract void mainEntry();
    • (Abstract method signatures may also have access modifiers like “private” or “public”)
  • Interface method signature: void mainEntry();

There is a key difference between an Abstract class method and an Interface method, however, and it is that classes extending an abstract class have the option to provide bodies for abstract methods from the parent class, whereas classes implementing an Interface must provide a body for every method in the parent Interface.

Some Key Points on the Abstract Definition Modifier:

  • Abstract classes must be extended in order to use them, they cannot stand on their own (be instantiated)
  • Abstract classes can have methods which are Abstract, Virtual, or just regular ol’ methods that contains code
    • As opposed to Virtual classes that can have Virtual or regular ol’ methods, but cannot have Abstract methods
  • Abstract classes can have member variables
    • Interfaces cannot
  • Abstract methods cannot have a code body in the class where they are originally defined
    • (As opposed to virtual methods that must have a code body)
    • Instead the signature is terminated with a semicolon like a regular line of code
    • Example: public abstract void methodName();  << see, no {} code body, just a semi-colon
  • Abstract methods cannot be static

So How Do Interfaces, Abstract Classes, and Virtual Classes Compare?

Generally you’ll see comparisons between Interfaces and Abstract Classes because both must be put into play by another class in order to be used, whereas Virtual Classes are more like just regular ol’ classes that can be instantiated and used as-is. In order to get them straightened out in my mind, however, I’ve included Virtual Classes along with the other two so I can more readily see their similarities and differences.

  • Instantiation:
    • Neither Interfaces or Abstract Classes can stand on their own
      • Interfaces must be implemented
      • Abstract classes must be extended
    • Virtual classes can stand on their own (be instantiated)
      • They can also be extended if the need arises
  • Methods:
    • All methods in an Interface are methods without bodies (just the method signature) and their body must be defined in the class that implements the Interface
    • All methods in Virtual classes will have bodies which can be well-defined or empty
      • Virtual within a Virtual class can be overridden
      • Regular ol’ methods within a Virtual class cannot be overridden (they’re just inherited by the subclass)
      • Virtual classes cannot have Abstract methods
    • Abstract classes can have Abstract, Virtual, or just regular ol’ methods
      • Abstract methods do not have a body
      • Abstract methods must be overridden if they are going to be used
        • If you’re not going to use an abstract method you do not need to create a body for that method in the subclass
      • Virtual methods can be overridden if you want to do so
      • Regular ol’ methods within an abstract class cannot be overridden (they’re just inherited by the subclass)
  • Member Variables:
    • Interfaces cannot have member variables (they have only methods)
    • Abstract and Virtual classes can have member variables
  • Extending and Implementing:
    • Interfaces can extend other Interfaces
      • Interfaces cannot implement Interfaces
      • Interfaces cannot extend Abstract or Virtual classes
    • Abstract and Virtual classes can implement Interfaces
    • Virtual classes can extend Abstract classes and other Virtual classes
    • Abstract classes can extend other Abstract classes
      • Abstract classes cannot extend Virtual classes

How To Know Which To Use

confused2

Here’s where some experience with Apex or Java coding most surely helps a ton. Fortunately I found a couple explanations, which I’ll paraphrase here, that really helped me understand how I might choose between an Abstract class and an Interface.

When thinking about the possible super classes that you may spin off of your underdog class, would you group those classes together based on a “thing” (a noun) or an “action” (a verb)?

For example, if your super classes were types of star ships (Enterprise, Gryphon, Drake, Apollo), then they would be “things.” If they will have similar actions (warp speed, cloaking, disk separation), then they would be “actions.”

  • For classes that are more “things,” use an Abstract class as the parent class
  • For classes that are more like “actions,” use an Interface

Another way to look at which to use is by where you want your implementation.

  • With an Interface you can share your methods with any class that implements your Interface
  • With an Abstract Class your methods are stored in one central place where all subclasses can access them, which avoids code duplication

Yet another way to compare the two:

  • When you can fully describe the class in terms of “what it does” without needing to specify any of “how it does it,” then you should use an Interface
  • If you need to include some implementation details, then you will need to represent your concept in an Abstract Class

And here’s a caveat:

  • If you add a new method to an Interface then you mush track down all the implementations of the interface and include the new method
  • If you add a new Abstract or Virtual method to an Abstract Class you can provide a default code body and then only classes that need to override the default actions need to be updated

    Features                                      Interfaces                                Abstract Class

    Multiple inheritance A class may implement several interfaces A class may extend only one abstract class
    Default implementation An interface cannot provide any code, just the method signatures. An abstract class can provide complete, default code and/or just the details that have to be overridden.
    Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
    Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface An abstract class defines the core identity of a class and there it is used for objects of the same type
    Homogeneity If various classes only share method signatures then it is better to use Interfaces If various classes are of the same kind and use common behavior or status then it is better to use an abstract class
    Speed Interfaces require more time to find the actual method in the corresponding classes Fast

     


Chaining It All Together

So now that I’ve figured out a thing or two while researching this blog I feel a whole lot more comfortable reading the Trigger Framework code I’m trying to understand. It’s a nice piece of work by Hari Krishnan (you can find it here) and is the framework that I’ve decided to use to build out the triggers needed in an org I’m working/learning in.

In Mr. Krishnan’s framework he has identified a couple Interfaces that define the methods that need to be present in the trigger code. While I found this concept fairly straightforward, what had me thrown was that he also uses virtual and abstract classes to implement those Interfaces.

But there is a wonderful reasoning for this: by implementing the Interfaces with abstract and virtual methods they become optional for the end classes (the classes that extend the abstract and virtual classes) where the actual grunt-work code resides.

For instance, he has defined several methods in his Interface ITriggerDispatcher. He then implements that Interface with a virtual class, and in that class he added a new, fully defined method. Finally the object-specific end classes extend the virtual class. In this end class only the methods from the virtual class that are needed are overridden. The other methods are ready to be used if the time arises that they are needed, but until such time they do not need to reside in the final class. Furthermore, when new functionality is needed, only the end classes need to be created or updated without having to change anything within the framework.

Pretty cool.

thSMHS9V79

 
Leave a comment

Posted by on June 28, 2017 in Apex

 

Tags: , , ,