Tag: Salesforce Apex

5 Strategies to get Around SOQL Query Limits

5 Strategies to get Around SOQL Query Limits

In Apex, there’s quite a few constraints that are strictly enforced because the platform is a shared multitenant environment. Quite a few of the limits result in runtime exceptions that can’t be handled.

For those familiar with Salesforce, it’s no secret that there’s a lot of limits. For example, there’s limits around the ViewState which were pretty painful to work around.

One of the first limits, I believe all new Salesforce developers hit is the limit for a maximum of SOQL queries that can be done. Continue reading

How to Choose An Apex Trigger Framework

How to Choose an Apex Trigger Framework

If you have been programming on the Salesforce/Force.com platform for any amount of time I’m sure you have come into contact with Apex Triggers. If not, Apex Triggers are units of code that execute whenever a database operation occurs. I’ve put together a post about Before and After Triggers that you should read if you aren’t very familiar with how triggers work.

Apex Triggers can get complicated very fast if your company has a very customized Salesforce Org. Apex Trigger Frameworks are a way of offering generic functionality that structures code in a certain way. If you were to use a building metaphor we could say that a framework is the supporting structure of the building – it’s the steel or wood shell that supports the building. Trigger Frameworks are very good at enforcing trigger best practices.

Why Use an Apex Trigger Framework

If you have ever worked in a customized Salesforce Org that is more than a few years old and has evolved over time, you can see the need for a lot of the best practices and the need for a framework that can abstract a way a lot of the structure. If you were to refactor the triggers and start to follow best practices, you could probably get away without needing to select one. However, trigger frameworks can help significantly reduce the amount of development effort as the org continues to grow more and more.

Here are some real advantages of using trigger frameworks:

  • Maintenance of Triggers is a lot easier if the trigger logic isn’t in the trigger.
  • Unit testing is a lot less complicated when the logic isn’t in the trigger.
  • A single trigger per object gives us a lot more control over the Salesforce Order of Execution.
  • It’s possible to prevent trigger recursion without building trigger killswitches all over the place.
  • It’s easier for teams of developers to work in a single code base if triggers are implemented consistently.

What do Trigger Frameworks Do?

Trigger Frameworks promote the idea of clean code and more consistent code and provide solutions to a host of other problems that are related to Apex Triggers.

Clear Organization and Structure

As a Salesforce implementation grows, the code becomes increasingly more difficult to maintain.

Recursion Management

Apex Triggers can be execute many times in a single apex transaction if something causes an additional update to occur in the transaction. Most of the commonly used trigger frameworks provide solutions to preventing recursion by using static variables or trigger kill switches. Review my post about the Salesforce Order of Execution if you’re not sure how or why this could happen. Common things to lookout for are Workflows, and Process Builders. Less experienced Salesforce Admins often create them without understanding the potential consequences, as developers we need to be able to handle situations where a trigger shouldn’t be called twice.

Encourages Separation of Concerns

One of the most important parts of software development is separation of concerns.

Separation of Concerns is usually achieved by encapsulation, or information hiding, and by using well defined interfaces. Layered designs are usually implemented as part of separation of concerns.

Criteria to Evaluate

When looking for a framework, you want something that is somewhat opinionated but not too difficult to use and maintain. It’s usually best if there isn’t one class that you have to modify every time you want to add or remove an apex trigger because there’s a good chance it might get missed.

You will also want to avoid using the Trigger static variables and methods within the Trigger Framework, so testing can be done a lot easier.

I believe that as developers we should try and avoid recreating the wheel, and should instead do a survey of the available trigger frameworks and apex trigger architectures before we try to build our own.

I recommend avoiding more complex patterns because Junior Developers and less seasoned developers won’t understand them. This is especially true if you are a consultant and building triggers for a client that doesn’t really have an Salesforce Developers.

Available Trigger Frameworks

There’s a bunch of different Apex Trigger Frameworks that are currently available. Dan Appleman, in his book Advanced Apex Programming, covers the one that they use at his company. Dan has generously provided example code from his book for free whether you purchased the book or not. The code can be found here.

Kevin oHara’s SFDC Trigger Framework is probably a pretty good starting point. It’s a good starting point because it’s relatively easy to understand for beginning programmers and it’s pretty simple to implement. It works by putting most of the logic into apex classes which the trigger’s can then call. For the most part, it’s simply a matter of pushing his code into your org and then extending “TriggerHandler” and implementing a few different overrides.

For most companies, it’s probably a good enough solution.

public class OpportunityTriggerHandler extends TriggerHandler { 
    public override void beforeUpdate() {
        for(Opportunity opp : (List<Opportunity>) Trigger.new) { 
            // do something
        }
    }
}

trigger OppportunityTrigger on Opportunity (before insert,
before update,
after insert,
after update) {
    OpportunityTriggerHandler handler = new OpportunityTriggerHandler();
    
    handler.beforeUpdate();
}

As you can see, it’s pretty easy to implement. There are a few things I don’t really like about:

  1. I don’t like using the Trigger related variables and methods outside of the Trigger. I like to pass in the Trigger.new List and Trigger.oldMap explicitly.
  2. The Max Loop Count throws an exception, so you need to make sure your code is all in a try/catch block or it could be rolled back.
  3. When referencing the Trigger variables in the external class they have to be cast to the proper sObject subclasses. I don’t think there’s a way around this it’s just kind of annoying.

Trigger Pattern for Tidy, Streamlined, Bulkified Triggers by Tony Scott works pretty well for a lot of use cases. I’ve built a few triggers with it and believe it’s being commonly used within the Salesforce Community.

Tony’s framework works by using an interface, structured Trigger Handler class, and a factory class. The Interface is relatively simple, like you would expect. Interfaces allow us to formally define the behaviour we are going to implement and allows the apex compiler to know whether one type can be cast to another.

Most of the logic we need to look at is implemented in ITrigger.cls and in TriggerFactory.cls. The key thing to notice is the bulk methods that has made available for us. There’s bulkBefore(), and bulkAfter() which are to be used for any querying or anything else that requires bulkification.

The only complaint about it, and it’s really minor, is that I’m not a huge fan of having to modify a factory pattern class every time I want to add a new trigger because I usually forget to do this and it takes me a few minutes to remember what I need to do.

Salesforce Order of Execution

Understanding the Salesforce Order of Execution

As Salesforce Developers and Salesforce Administrators, we need to understand how the system will process and validate the data that we are inserting or manipulating. As any system does, the rules follow a general pattern that’s known as the Salesforce Order of Execution. Continue reading

How to Automatically Convert Leads in Apex

How To Automatically Convert Leads In Apex

In the blog post “What’s the difference between a Lead and Opportunity?” I spent a bit of time covering how leads are converted into accounts, contacts, and opportunities.

Basically, a lead is converted when the sales person thinks that there’s actually an opportunity to sell them something. In a lot of cases, it might make sense of for leads to be automatically converted after a field is set to a certain value. For example, a lot of companies might want to automatically convert a Lead as soon as the Sales Rep has completed ANUM or BANT.

To convert a Lead into an Account, Contact and an Opportuninity we need to make use of the Database.convertLead method.

5 Incredible Resources For Learning to Program Salesforce

5 Incredible Resources for Learning to Program Salesforce

Salesforce is an incredibly large and customizable platform with hundreds of different features. Learning to use Salesforce can be difficult, but learning to program and manage Salesforce is even more daunting. Below I’ve provided you with the best resources I could find on programming Salesforce.  Before jumping into learning to program apex, I recommend you register for a demo org and watch a few of the different product demos.

When I started learning how to use Salesforce Apex in 2013, I was amazed at the hundreds of different online resources available. Literally, there are thousands of different sites. Over the last two years, I’m sure there’s been even more resources. Salesforce has developed its own “learning portal”, and there’s been a few new books that have come out.

SFDC99

One site, in particular really stood out to me which was SALESFORCE CODING LESSONS FOR THE 99%. David has written very good and detailed tutorials that anyone should be able to follow and implement. I understand that David lead some great sessions at Dreamforce 2014; I wasn’t able to attend any of them though.

Trailhead

At Dreamforce 2014, Salesforce introduced Trailhead. A while after Dreamforce, I wrote a post about my thoughts on Trailhead. Trailhead is an incredible resource that I wish was around when I had first started using Salesforce. Over the last year, it’s really exploded and now offering a ton of different paths to learning about Salesforce.

Bob Buzzard Blog

No list would be complete without the Bob Buzzard blog. Keir has written dozens of blog articles that I have bookmarked about different Salesforce topics. His posts are primarily about visualforce and apex, although he has started writing quite a bit about Salesforce Lightning and Trailhead. He’s also written a book about visualforce and led some great sessions at Dreamforce. I believe right now Keir has almost all of the Salesforce Certifications.

OyeCode

Harshit Pandey previously worked at Salesforce as a Technical Architect. He has some incredibly basic blog articles, and some incredibly technical articles as well. One of my favourite series so far is his section on Salesforce Technical Architect Best Practices.

Jeff Douglas Blog

Prior to becoming a Salesforce Employee Jeff wrote some incredible posts about apex and visualforce. One of my favourite posts is his post about having “Fun With Salesforce Collections“.

Additional Salesforce Training Resources

  • Force Platform Fundamentals is Salesforce’s introduction to the Force.com Platform. There’s quite a bit of discussion about building metadata (creating objects, fields, custom workflows, approval process), security, and reporting. Overall, it’s pretty good but also very daunting. The pdf has about 400 pages.
  • Visualforce Developers Guide is pretty much a must for any developer that will develop pages in Salesforce.
  • Apex Workbook covers a lot about the syntax, fundamentals, and limits the Salesforce have placed in the language and on the platform.
  • Salesforce University provides some in person and online training. I haven’t taken any of the training, but it seems like it could be pretty good based on some of the Hands on Training I’ve done at Dreamforce. Prices also seem to be pretty high, and in US Dollars
  • On Youtube, there’s a lot of different Dreamforce Presentations many of which are very good and still pretty relevant.
  • Also review my blog article about about Using jQuery with Visualforce.