Preface – This post is part of the Core Apex Tools series.
I still remember the exact moment I fell in love with coding. It happened when I first discovered dot notation. I hope you too can have this joyful moment with Apex some time!
If you’ve ever made validation rules, workflows, or formula fields, chances are you’ve already used dot notation in your career. Dot notation simply lets you traverse objects through relationships and fields:
Decimal companyRev = myContact.Account.Revenue; User friendCreator = myContact.Best_Friend__r.CreatedBy;
The beautiful thing about dot notation in Apex is that there are no restrictions! You can traverse as many relationships as you like and in any direction! There’s nothing more frustrating than building a workflow rule only to find that certain relationships can’t be traversed!
Here’s an example of traversing downwards using dot notation. This isn’t possible without Apex!
List<Opportunity> opps = myContact.Account.Opportunities;
The final use of dot notation is that you can call an object’s instance methods:
Integer numOpps = opps.size(); // A List instance method! String iLoveCaps = myContact.FirstName.capitalize(); // This is a String instance method. The result is DAVID
Very soon you’ll be creating your own instance methods!
Next post: Loops – FOR and FOREACH loops!