Trapdoor In The Sun

Alan Shanahan, Technician & Consultant


2 Comments

Force.com: Apex Styleguide, Part 3

Click here for Part 1 of this series.
Click here for Part 2 of this series.

Here, I’m going to take a look at the condition part of the if statement. In particular, how best to write a complex condition to allow for readability and easy code maintenance. Sometimes even just a small number of ANDs and ORs can be easy to write but difficult to untangle later. Add in some brackets for changes in operator priority and the picture becomes even worse. I will refrain from filling up this post with words because I think the example below will provide most of the colour and information I’m trying to impart on the topic.

if (conditionA || (conditionB && conditionC) || (conditionD || conditionE)) {
  doSomething();
}

Figure 1, above, equates to the following:

if A OR (B AND C) OR (D OR E) then do something

When you substitute the conditions for real-world variables, function/method calls or complex structure sub-fields, the results can be less than legible. But, apply a little indentation and split your conditions up and you suddenly have some clarity.

if (
       conditionA
       ||
       (
           conditionB
           &&
           conditionC
       )
       ||
       (
           conditionD
           ||
           conditionE
       )
   ) {
  doSomething();
}

Figure 2, above, is functionally identical to Figure 1. Do you think it’s more readable? Easier to maintain?

A little tip for those engaged in writing complex Force.com custom formula fields with if statements: try using the same method .

Advertisement


Leave a comment

Update: New Salesforce.com function to provide 18-char IDs

I blogged in the past on the subject of Salesforce.com IDs: click here to see it.

The wonderful thing is that SFDC were listening! Not just to me, but I was a voice in the crowd. They responded in the Spring ’12 release with a new function to be used in formula fields:

Syntax example: CASESAFEID(Id)

Official documentation link: http://login.salesforce.com/help/doc/en/customize_functions_a_h.htm#CASESAFEID

It’s that simple. Just set up a new custom field with this as the formula and use it in your reports.

 

[Note: SFDC = SalesForceDotCom]