Trapdoor In The Sun

Alan Shanahan, Technician & Consultant


3 Comments

Force.com: Apex Styleguide, Part 5

Click for Part 1, Part 2, Part 3, Part 4 in this series.

Arrays or Lists?

With this post I am, strictly speaking, stepping outside of the pure topic of style. It’s one of those grey areas.

It’s that whole idea of whether to use Array or List data structures in your code. If, like me, you come from a background of programming languages where the first element of an array is element # 1, rather than element # 0, then you may also find List structures a little more intuitive because you usually don’t have to worry about element numbers when you iterate.

From the Apex language viewpoint, arrays and lists are interchangeable; you can declare a list and treat it as an array and vice-versa. Try it yourself if you don’t believe me:

public class BlogStyleGuide5 {

  // -----------------------------------------------------
  // The first method declares and populates an Array,
  // then iterates through it as a List.
  // -----------------------------------------------------
  void iterateOLI1() {

    OpportunityLineItem[] arrOLI = [
      SELECT Id, Quantity
      FROM OpportunityLineItem
    ];

    for (OpportunityLineItem iOLI : arrOLI) {
      Id      wrkId  = iOLI.Id;
      Decimal wrkQty = iOLI.Quantity;
      // Do something
    }

  }

  // -----------------------------------------------------
  // The second method declares and populates a List,
  // then iterates through it as an Array.
  // -----------------------------------------------------
  void iterateOLI2() {

    List<OpportunityLineItem> lstOLI = [
      SELECT Id, Quantity
      FROM OpportunityLineItem
    ];

    for (
      Integer i = 0;
      i < lstOLI.size();
      i++
    ) {
      Id      wrkId  = lstOLI[i].Id;
      Decimal wrkQty = lstOLI[i].Quantity;
      // Do something
    }

  }

}

If you were to adopt my preference for List structures rather than Arrays, you might end up having to re-code. That’s why I mentioned that this topic steps a little outside the realm of style. Therefore, please use care if you take this route. Ensure you test your changes thoroughly according to standard “good practice”.

Any comments on the above?


3 Comments

Force.com: Apex Styleguide, Part 4

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

This one is a little easier on the brain.

From time to time, you will come across a scenario where one structure will need to be copied to another, and there’s no option but to do it “the hard way”, as in the example below. But do you want it to look good?

// Copy temporary record to database object structure
if (copyToRecord) {
  recordObject.Name = tempObject.Name;
  recordObject.Custom_Field_String_13 = tempObject.Custom_Field_String_13
  recordObject.Address_Line_1__c = tempObject.Address_Line_1__c;
  recordObject.Address_Line_2__c = tempObject.Name;
  recordObject.City__c = tempObject.Name;
  recordObject.Country_Code__c = tempObject.Name;
  recordObject.Postcode__c = tempObject.Name;
  recordObject.Contact_1_First_Name__c = tempObject.Name;
  recordObject.Contact_1_Last_Name__c = tempObject.Name;
  recordObject.Contact_2_First_Name__c = tempObject.Name;
  recordObject.Contact_2_Last_Name__c = tempObject.Name;
}

Figure 1, above, shows the raw code as many people would write it. Nothing wrong with that.

// Copy temporary record to database object structure
if (copyToRecord) {
  recordObject.Name                    = tempObject.Name;
  recordObject.Custom_Field_String_13  = tempObject.Custom_Field_String_13
  recordObject.Address_Line_1__c       = tempObject.Address_Line_1__c;
  recordObject.Address_Line_2__c       = tempObject.Address_Line_2__c;
  recordObject.City__c                 = tempObject.City__c;
  recordObject.Country_Code__c         = tempObject.Country_Code__c;
  recordObject.Postcode__c             = tempObject.Postcode__c;
  recordObject.Contact_1_First_Name__c = tempObject.Contact_1_First_Name__c;
  recordObject.Contact_1_Last_Name__c  = tempObject.Contact_1_Last_Name__c;
  recordObject.Contact_2_First_Name__c = tempObject.Contact_2_First_Name__c;
  recordObject.Contact_2_Last_Name__c  = tempObject.Contact_2_Last_Name__c;
}

Figure 2, above, is a “cleaned-up”, column-aligned version of the same code. It took very little effort, but suddenly there’s more clarity.

OK, call me petty, but what do you want your code to say about you?


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 .


3 Comments

Force.com: Apex Styleguide, Part 2

If you haven’t already seen Part 1 of this series, click here to go to it.

Example 2, if/then/else Statements in Apex:

This article deals with the humble if/then/else statement, specifically the executable part of the statement. As before, I’m writing in Apex code, so there may be minimal syntactical differences between this and similar, related languages e.g. C & variants, Java, etc.

We can start with a simple, common binary use of the if statement:

if (a == b) runSomething();
else runSomethingElse();

Figure 1, above, is a simple case of “if a = b then run something, otherwise run something else“. It looks perfectly fine.

if (a == b)
  runSomething();
else
  runSomethingElse();

Figure 2, above, is almost identical to Figure 1 except that the executable part of the if and else clauses are on separate lines and indented. A little better. More readable, perhaps, and functionally identical.

if (a == b) {runSomething(); } else { runSomeThingElse(); }

Figure 3, above, has expanded on Figure 1. The addition of block braces around the executable sections serve to demarcate the runnable parts of the code.

if (a == b) {runSomething(); andSomethingElse(); } else { runSomeThingElse(); andRunAFourthThing(); }

Figure 4, above, is an example of where the programmer has added some extra method calls into the two executable blocks. This would not be possible for Figure 1 and Figure 2 above without the addition of braces.

if (a == b) {
  runSomething();
}
else {
  runSomethingElse();
}

Figure 5, above, is where we FINALLY come to the version that I’m happy with. The if and else clauses are on their own lines, block braces surround the executable sections of both clauses and indentation completes the picture.

if (a == b) {
  runSomething();
  andRunSomethingElse();
}
else {
  runSomethingElse();
  andRunAFourthThing();
}

Figure 6, above, is a clear illustration of how easy it is to add two method calls without upsetting any of the surrounding lines of code in Figure 5. No braces need to be added because they are already there. The value of this style is that you may wish to add multiple lines within any of the code blocks; this makes it very easy to do and retains code legibility.

As ever, please feel free to post your comments, whether you agree with me or not.


8 Comments

Force.com: Apex Styleguide, Part 1

Style, in any artistic or professional endeavour, is impossible to quantify, define or measure. It’s highly subjective and can often be controversial. So I’m going to push my own opinions in this, the first of several posts on the subject of coding styles. They won’t be complex articles, merely a look at what I think is poorly-written code versus how I believe it would be better presented. There will be no attempt to discuss whether the code in question is inherently “correct”; merely that it looks difficult to read and is hard to maintain. The aim is to turn both of these problems around, thus making the code easy to read and maintain.

In cases where there may be several variants, I will present them, and give a synopsis of how “stylish” I think it is.

Your comments, as always, are very welcome on this topic.

Example 1, SOQL Queries in Apex:

Let’s start with a common code segment whereby a SOQL Query is run and the resultant record set is returned into a list data structure.

List<Custom_Object__c> lstRecords = [select id, field1__c, name, number_field__c from custom_object__c where name like 'Smith%' order by lastname, firstname limit 100];

Figure 1, above, shows how an “undisciplined” programmer might put together a code segment that retrieves a record set from a SOQL query. In an IDE or other editor, this might well appear as a single line and you would have to scroll right to see the full detail.

List<Custom_Object__c> lstRecords = [select id, field1__c, name, number_field__c, an_additional_field__c, and_another__c from custom_object__c where name like 'Smith%' order by lastname, firstname limit 100];

Figure 2, above, would show the result of adding two additional fields to be retrieved by the query. Not very pretty.

List<Custom_Object__c> lstRecords = [
  SELECT
      Id
    , Field1__c
    , Name
    , Number_Field__c
  FROM Custom_Object__c
  WHERE Name LIKE 'Smith%'
  ORDER BY FirstName, LastName
  LIMIT 100
];

Figure 3, above, is how I would put this snippet together. I find this more professional-looking, much easier to read and far easier to modify. The following improvements have been made:

  • the outer data structure is separated from the inner SOQL statement
  • code is indented in a useful way
  • keywords are uppercase for readability
  • query clauses are split onto separate lines
  • fields are also split onto distinct lines and vertically-aligned to enable simple editing
  • field names have been retyped with appropriate letters in uppercase

You may not agree with the word “improvement”; please let me know if you don’t, and the all-important reason why.

List<Custom_Object__c> lstRecords = [
  SELECT
      Id
    , Field1__c
    , Name
    , Number_Field__c
    , An_Additional_Field__c
    , And_Another__c
  FROM Custom_Object__c
  WHERE Name LIKE 'Smith%'
  ORDER BY FirstName, LastName
  LIMIT 100
];

Figure 4, above, shows the result of adding the same two additional fields as in Figure 2. The results speak for themselves.

More code examples to follow soon. Why not follow the blog to get email notification of new posts?

Acronyms used above:
SOQL = Salesforce Object Query Language (a proprietary variant of SQL)
IDE = Integrated Development Environment (e.g. Eclipse, MS Visual Studio, NetBeans, JDeveloper, Xcode, etc.)