CLEAN CODE - Apex Edition (Volume 2)

In case you missed Volume 1 of Clean Code - Apex Edition...

We'll start right back up where we left off with tips and pointers on how to make your code better, easier to manage and easier to read...

Method Length

In general, you want to keep methods as short as possible. Often times as we write code we find that the method becomes longer and longer and we can naturally just refactor the method into two or more. As Uncle Bob would say:

The first rule of [methods] is they should be small. The second rule of [methods] is that they should be smaller than that. - Uncle Bob Martin - Clean Coder

The goal is always to do one thing and do it well. That makes it easier to read, easier to troubleshoot and less susceptible to breaking as the code evolves.

Commented Out Code

Commented out code serves no real purpose. If you commented it out - you commented it out for a reason. Either you refactored something and wanted to make sure this code was no longer used or it was past its prime. The problem is that you are the one who commented it out and I bet you a nickel you won't remember 3 days from now why you did it. The code then gets checked in and guess what - nobody else will have the guts to ever remove it. They will think "oh man, this is probably too important to delete, someone must be using it or intends to finish it." Every time anyone sees it they waste brain cycles thinking about it.

Approach 1 - Delete it and know that it is there is source control one revision back (hopefully you're using source control)

Approach 2 - When I comment out a variable or a block of code I put my initials next to it with a comment that says something like:

//SFG - commenting out as this has been refactored - if still here on July 30th, 2015 please delete

Then as part of my code review and check-in routine I made aware of those things. Many time it is as simple as variables that are defined that are never used. Methods that have since become redundant but they still clutter the code. Get rid of them!

Code Commenting

  • Avoid obvious code comments as they just clutter things up and add waste. Take the example below

//deletes the employee passed in

public Boolean deleteEmployee(Employee emp)

So how does the above help anyone? It doesn't. In this case there should be no comment or give more details about what happens - is it a soft-delete, what happens if it fails, etc.

  • Along the same lines (or at least related) - when you checking your code to Source Control (SVN, TFS, whatever) - put some true comments in there about what changed, why etc. I use Jira as my ticketing system so the first thing I do is preface every checkin with the Jira ticket #. That way a year from now, someone can not only go look at Jira and see the original bug or feature request but they can then tie it back to to my checkin. One of my pet peeves is when people checkin 10 files at a time and put the same comment for all of them "fixed some bugs". Really? Thanks - that is a big help. Now I need to go diff those 10 files and figure out which one(s) had anything to do with the original request(s).  It just goes back to the Boy Scout rule - leave the code in a better place than we you found it.


DRY Principle

The goal of your code is to not repeat yourself. If you are repeating yourself that is your first and best clue there is a better way to do this. The DRY Principle states (snippet from Pragmatic Programmer: From Journeyman to Master):

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system



Clean Code - Apex Edition (Volume 1)

A lot of the thoughts, ideas and suggestions below come both from Salesforce documentation, computer legends like Uncle Bob Martin, Martin Fowler and just general experience. I've done my best to credit these sources both in the article and in the references section. If I have left anyone out, it was not intentional - just post a comment and I'll get it updated. This is Volume 1 of a series.

Triggers (one per object and have only a handful of code)

  • Only use one trigger per object. Obviously if you install other apps, they come with their own triggers but just from a debugging and readability standpoint - use one trigger per object.
  • DO NOT put logic in your triggers - triggers should be used to manage execution order and delegate all else.
  • You can never know or guarantee which order a trigger gets executed in, it is therefore much easier to manage/debug flow when you are only looking at one trigger.


Kevin O'Hara (super genius and MVP) has an awesome resource here on Github showing a trigger and a triggerhandler.

Class Names

Ever looked at code someone else has written or even better, you wrote 6-8 months back and try to make sense of it. It can be hard - especially if you have the added pressure of needing to fix something fast. As Uncle Bob says "clarity is king". Classes and object for that matter should use nouns or a noun phrase as their name. Examples: Employee, HelpPage, Customer, ZipCodeParser. Remember from grammar school that nouns represent things. 

A class name should not be a verb (verbs are for your method names).


Method Names

Class names start with nouns or noun phrases. With Method Names we want to use verbs (word used to describe an action, state, or occurrence). We can also use verb phrases. Examples:  deleteEmployee, setName, getName


You've got a great sense of humor (or at least you think you do). Don't put it in your code.

Don't give your variables, methods, classes cute/funny names. Don't use slang. The same goes for code comments - be professional. I can't tell you how many times I look at code and see comments in try/catch blocks that says "if we got here, something went wrong". Thanks, that was a big help in figuring out what the problem was. 

I've seen good programmers that use code comments while they develop and troublehsoot. Anything they don't want to get checked in or was meant as just a reminder they put their inititials in front of. For example:

// SFG - need to understand why this list is being populated and never used anywhere

Before checking in the code you just do a quick search for "SFG" and if you still have those in there, you're not done - or you need to create work items or tickets to come back and review those things. 



When to use SOSL vs SOQL in Salesforce

Both SOQL and SOSL are extremely powerful query tools in Salesforce but they have different uses. In this article we'll explore what these two query languages are best suited for and how to take advantage of them. First let's start out with some simple definitions.

SOQL (Salesforce Object Query Language)

If you are at all familar with SQL (Structured Query Language), SOQL is very similar to SQL in that you use to a SELECT commond to speficy a source object (example Lead), a list of fields to grab, and the conditions for selecting the rows.

Select Id, LastName, FirstName, Company, Email from Lead where email = ''

Just like any database, Salesforce uses indexes to make queries return results faster. SOQL and SOSL use different indexes.

What are some common indexes that can be used to make a SOQL query more efficient? Answer:

  • Primary Keys (Id, Name, Owner Fields)
  • Foreign Keys (lookup and master-detail relationship fields)
  • Custom fields marked as External ID or Unique - often times these are used to tie Salesforce records to external systems.
  • Audit Dates (i.e. LastModifiedDate)

Fields that CANNOT be indexed (and part of the reason SOSL is important) include:

  • Long text fields
  • Multi-select picklists
  • Binary fields (i.e. file, blob, encrypted text)
  • Currency fields (when multicurrency is enabled)

SOSL (Salesforce Object Search Language)

SOSL is used to construct text searches. SOSL's true power is that it enables you to search text accross multiple objects whereas SOQL is just a single object. Example: 

FIND {Salesforce General} IN Name Fields RETURNING lead(name, phone)

When to use SOQL
When to use SOSL
You know which object, fields you want to retrieve
You don't specifically know which object or field the data resides in but you need an efficient way to find the records
You want to get a count of the number of records that meet a specific criteria. i.e. where OwnerId = X
You want to get data from multiple objects and field in the most efficient way - the objects may or may not be related to one another.
You want to sort the results as part of the query
As described above when you are trying to query data in fields that cannot be indexed yet you have a large data
You want to get data from number, checkbox or date
You want to get data from a single object or multiple objects that are related to each other (i.e. Accounts and Contacts)

Ever wondered what a punchcard looked like?

I was reading a book the other day about computer history and so I thought it would be fun to see an actual example of what a punchcard looked like and how they worked. As an homage to our forefathers I decided to mix some old and new. Below you've find some Apex written on a DEC-029 punchcard.

DEC-029 Punchcard with Apex by @larsnielKind of cool. Even better though, go here to create your own. And you thought it wasn't fun to use the Developer Console to debug your code! Look at how far we've come...



SOQL Query Plan Tool

Salesforce added the Query Plan tool as part of Summer 14'. It's actually a lot of fun for those of us that come from a SQL background and love to get our hands in the guts behind the scenes. It is also really helpful and interesting if you don't like guts. In this article, we're just going to ease into things and show you how to launch the Query Plan Tool and then in Part II we'll go into more detail about what it all means. Anytime you write a SOQL statement, run a report or even just view a record in Salesforce - the underlying framework (i.e. the database layer) has to come up with a battle plan on how to get the data.

Click to read more ...


What is the Lightening process Builder?

With Spring 15' comes the release of the highly anticipated Lighting Process Builder. For those not familar, it is a really slick way to graphically draw out automated tasks inside Salesforce. Salesforce has been working really hard over the last couple of years to give everyone (technical and non-technical) the ability to make productvity advancements with Salesforce. 

Before Lightening Proces Builder, administrators and developers would have used a combination of workflow rules and apex to build out automated tasks and processes. The beauty here is that you can do this in one place rather the than creating multiple rules. In addition, more actions are available to you than a traditional workflow.

The Lightening Process builder allows you to create a record and or post to chatter


See a sample of the user interface below, it's extremely inuative.


The Lightenging Process Builder doesn't fully reaplce validation rules and approval processes; however, it sure does just about all the same things in a very easy to use way. The only real exception that I've come accross is the need for Outbound Messages.


SOQL Offset

Hi guys, sorry - it's been a while. Lots going on lately but I wanted to catch everyone up on something I found handy the other day - the OFFSET clause on a SOQL query. It was added as part of API 24.

OFFSET can be used as an efficient way to handle large result sets


Use Case

 You want to sit down with your significant other and watch a marathon of Walking Dead. I'm talking all the episodes from the pilot to the most recent episode. There is just one catch - you watched the first four epidoes last weekend and you want to skip straight to episode 5 "Wildfire" and you're using SOQL. Okay, I realize this is far fetched but we've made it this far so let's stay with it a little longer and see how Offset can help us write a SOQL statement that will help us out...

Offset is like saying "give me the first X records but skip some records before you start the counter"


Select, Id, Name, Synopsis, OriginalAirDate from Walking_Dead__c OrderBy OriginalAirDate Limit 100 Offset 4

This will give you records 5 through 100.

Best Practices

  • Use an ORDER BY clause when you use OFFSET to keep your results consistent. The row order of a result set that has no ORDER BY clause isn't going to be stable.
  • It's also smart to use a LIMIT clause in combination


Things to keep in mind with SOQL OFFSET

  1. The maximum offset is 2,000 rows (as of Spring 15'). If you try to pass in a number larger than 2,000, you'll get a nice little NUMBER_OUTSIDE_VALID_RANGE  in return.
  2. Offset is intended to used as part of a top-level query. It's not meant (and not allowed) in most sub-queries. If you try to add an Offset in a sub-query you will often get a  MALFORMED_QUERY.
  3. Offsets ARE NOT A REPLACEMENT for using queryMore()



SOQL Using Scope (new in Winter 15')

SOQL query filtering with the new USING SCOPE clause

One really useful thing added in SOQL with the Winter 15' release is the ability to a Scope clause to a SOQL query. A common task we all find ourselves with at various times is the need to grab a group of leads or accounts for example and perform an action on them. More specifically if you use territories, you may need to get a list of all the accounts in Territory X and do something with them.

Prior to Scope, you would attack the problem backward. i.e. what makes up Territory X (who is in it, what is the territory region etc etc.) You would then build a query around those parameters. With scope there is now an easier option. Scope takes one enumeration values { Everything, Mine, My_Territory, My_Team_Territory or Team}

Example (grab all the accounts that belong to you)


Example (grab all the accounts that are in your territory) 

SELECT Id FROM Account USING SCOPE My_Territory 


Note: This also works on Customer Objects


Salesforce Dataloader Heap Space Exception

If you are trying to upload and download large volumes of information using the Salesforce Dataloader you might run into this error. "Java Heap Space" from the Data Loader UI version 21.0 onwards This is common especially if what you are loading is large attachments (PDFs, Powerpoints etc). The Salesforce Dataloader is a Java application that runs on the local Java Virtual Machine (JVM). The heap size is essentially how much memory is allocated to the application while it runs. Starting with version 21 of the Salesforce Dataloader the heap size is more restrictive than in past versions. There are some quick fixes to get your around this issue.

Click to read more ...