Here is how I debug my issues. In most cases I would only make it to step 2 before I solve my problem.
Step 1: Explain it to your Rubber Duck
I try explain what my code is doing to my rubber duck. A lot of the time I figure out the problem when I'm explaining the code to someone else. (If exceptions are involved, take a look at your code at the line numbers reported and consider what could have generated the exception.)
Step 2: System Debugs
Debug log recording in Setup is turned on for your User via: Setup > Monitoring > Debug logs
. See here for more information.
I would place temporary debug statements such as System.Debug('>>>> the value of x is ' + x);
within my code to make sure that the code is executing the way I think its working. Individual SObjects, Maps of SObjects and Lists of SObjects can all be appended and that shows you all populated SObject fields.
The >>>>
is a unique string that usually doesn't appear anywhere else in the log files. This allows me to quickly find my debug output. (Logs are truncated after 2M bytes of output - there are work-arounds for this.)
Step 3: Use the Developer Console
The Developer Console is a great tool for debugging. You do the following things (and more) with the developer console
- View Logs. This is another way of viewing debug output.
- Execute SOQL. This can be used to verify that the SOQL in your code is returning the correct information
- Execute Anonymous. Apex code can be run directly from the dev console
- Checkpoints can be added in the code (maximum of 5 per class), which will allow you to stop the code executing and to see variable information.
See Josh Kaplans YouTube video for more info on the dev console
Step 4: Create a Unit Test
A unit test is a great way to figure out what is going on with a piece of code. It allows you to:
- Execute your code in an environment with no other data
- Create test data that you can use over and over again.
- Use asserts to check your code e.g.
System.assert(contacts.size() > 0);
or System.assertEquals(expectedX, actualX);
Step 5: Take a break
I find myself getting frustrated when I have been looking at the same problem for a long period of time. This does not help solve the problem, it can actually make it harder to clearly see what is going on in the code. Take a break for a while and you may find that when you look at the problem again it makes more sense.
Step 6: Ask for help
If you have done all the steps above and reached this point then you most likely need help. This is where a colleague or stack exchange come in. Make sure when asking a question that you clearly state your problem, provide enough information to make it understandable to others and if you are providing a code sample make sure that it is formatted and easy to read.