Debugging Apex Code
Debugging Apex code can be challenging for both new and experience Apex developers However here are the steps I’ve learned when I’m writing some code, and it doesn’t work.
Explain the problem to yourself or a coworker
A lot of the times I’ve figured out a problem simply by explaining the code to another person or out loud to myself. Try it out you’ll surprise yourself how often this works.
System debug statements
Utilizing the debug log by navigating to Setup > Monitoring > Debug Logs and adding in the User you want is a great way of debugging an issue. Inside your Apex Class or Trigger you would add System.debug() statements for example:
trigger HelloWorldTrigger on Contact (before insert){
for(Contact cnt : Trigger.new){
cnt.FirstName = 'Jon';
System.debug('Contact First Name: ' + cnt.FirstName);
}
}
System.debug() simply prints the value of anything you put inside it. It’s very useful for printing out the values of SObjects, Maps, or lists and tracking the value of a variable throughout your code.
Developer Console
With the developer console you can do a lot of things to help debug coding issues. For example:
- View Logs
- Run SOQL queries
- Execute Anonymous Apex
- Checkpoints a max of 5 per class
Create Unit tests
This goes without saying, but you should be creating tests class for all your code regardless, but it is also a great tool for debugging. You can create reusable test data on the fly and use asserts to check your code for example:
System.assert(!nameOfList.isEmpty());
System.assertEquals(expected, actual);
Take a break
This one I find a lot of junior developers skip, but after long periods of debugging you will find yourself mentally exhausted. Just by taking a break and taking a walk, getting some coffee/tea to clear your mind can go a long way.
Ask for help
If you have exhausted all other options, then ask your highly intelligent and sometimes arrogant :P coworkers. Everyone needs help to solve a problem at times so don’t be afraid to ask, but you also want to respect others time, by being concise and clear to what your problem may be.
Happy coding,
-Korben