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?

Advertisement


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.)


Leave a comment

Developer Maturity

Thirty-odd years ago, I wrote my first lines of BASIC code on an Apple II computer donated to my secondary school by some local businesses. We were the first of our school and, to some degree, our generation to have access to such a device. I was hooked from the word go. All these years and a few dozen jobs later, I can tell you I’ve seen the full spectrum of good and bad in the world of programming; I may even have contributed to the bad side, but I live in hope that most of what I produced was leaning towards the better side of things.

But I can see definite steps in my progression in those intervening years; let me focus on programming itself, or “development” as the industry likes to call it. Today, I have a very different mindset to that of my teen years. My young naive self revelled in the idea that you could type an arbitrary set of instructions into a machine and it could do the most marvellous things. Coding was an end in itself! It existed just so that beautiful programs could be written and run. I had a lot to learn.

Then I started working in the real world. My programs were now being used by real people, in a real business, every day. There was a huge amount of job satisfaction in that idea. Everything changed. My “hobby” was now something to take seriously and it had to perform to a new standard. But I didn’t fully realise that and I still saw programming as an isolated pursuit with its own intrinsic value; in my mind it was a primary activity with its own purpose rather than an enabler. This illustrated an immaturity in terms of my business viewpoint.

Many years later, I’ve managed programmers and development teams. Still doing that. I’ve designing solutions for customers that are implemented by these teams. I’ve seen and reviewed a lot of code. In that sea of code, the full spectrum of quality exists. Some bad practices can have a subjective slant to them, but other bad practices are just plain bad. I’ll tackle the subject of quality later, it’s just too big to even contemplate here. But one point on quality is worth reiterating here and now: quality is everyone’s responsibility. I won’t explain that further, I believe the words do that for themselves. You own quality. You own problems created by your programs, no matter how trivial. At least to some extent. You owe it to your team to properly ring fence and test scenarios your programs are supposed to handle. You owe it to the customers who are paying for your development efforts.

And what I have seen is a set of behaviour patterns that seem to be repeating.

Firstly, there is an obvious disconnect between some programmers and the end user they are programming for. Think about users. Someone will sit in front of a screen and use your programs. They are real people, no matter how distant they are, or how imaginary they seem.

Another misalignment I’ve seen is that some programmers don’t conceive that data represents real world things. Financial data represents money, real money, not imaginary money. This is important to customers. It’s their money, the life blood of their business, which would simply curl up and die without it.

Polish! Polish your code. Polish the user interface. Try to break your programs. Keep trying until they no longer break.

Open your mind. Let go. Don’t be afraid to rework what you’ve written. The best writers and authors do this regularly; that’s why they’re the best. Coding is not an end in itself, it’s a means to an end: the business aim is the end. Code is just an enabler.

Do these things…

…and you’ll be all grown up.

[Note: I’ve emphasised “some programmers” in this piece. I’ve worked and continue to work with many superb developers. It’s worth mentioning.]