Developers

Salesforce Code Formatting Best Practices

By Alex Crisp

When we talk about code formatting, we are talking about the positions of line breaks, how many characters should go on a line, and everything in between. For something so simple, it is actually one of the most hotly-debated arguments when it comes to programming. But why?

Well, the way we format and style our code has much more of an impact than you might initially realize. Let’s take a closer look.

The Basics

When someone new comes to a codebase, the first thing they’re presented with is how the code has been written, which should provide subtle clues as to the original intent, allowing the reader to easily read and understand code that is foreign to them – this is especially true if they’re unsure of what exactly a piece of code does. And let’s face it, as hard as we try, having complete and up-to-date documentation is a rare occurrence!

Programming is a tough mental exercise. Being able to put your brain into ‘cruise control’ while reading, allows us to more easily understand what’s going on at a faster rate. Code that is formatted inconsistently will break this flow and make the task far tougher than it needs to be.

So, having a formatted codebase is objectively better – that’s something we can prove with science and statistics – but what exactly that format should be is very subjective. Instead of getting caught up in an endless cycle of meetings to decide how many spaces should go before or after a bracket (and the heated debates that will cause!), we can choose to adopt a well known formatter that slots straight into our development tools and decides for us.

This is called an opinionated formatter, because it has its own opinions and simply doesn’t care what we think. This may seem like a curious choice at first, but by removing choice and customizability, and by following a well-adopted set of guidelines, we can remove the friction that could occur in a team, not only in deciding guidelines, but also in putting them into practice!

Making Your Code “Prettier”

Introducing Prettier – our opinionated, code-formatting savior! Prettier is well used across the entire tech industry, including Facebook, Salesforce, PayPal, Spotify, Discord, and so many more.

Prettier is supported across all Salesforce programmatic languages, so regardless of whether you’re writing a Lightning Web Component or building its backend in Apex, you can be sure that Prettier is keeping your code looking nice and readable, with little to no intervention as you go.

Installing Prettier is also very easy; if we’re using VSCode, we can find the Prettier Extension on the extensions marketplace. For Prettier to be able to format Apex, we first need to install an extension, which is also super easy – just follow the command below (make sure you have node installed!).

npm install --save-dev --save-exact prettier prettier-plugin-apex

Now that we know how to install Prettier, let’s take a look at exactly what it does. In its simplest terms, it strips your code of all styling and rewrites it in the way it thinks is best. We can even set it to do this every time we save, which is great as it allows us to write our code in a way that feels natural. Prettier then does the legwork to make it conform to a style standard. Now let’s take a look at the specifics of what it considers to be “good”.

The main bulk of Prettier’s magic happens when the number of characters reaches a certain threshold – it will attempt to split them onto multiple lines to increase readability. This is 80 characters by default, which is a throwback to the old days of programming by terminals. However, I personally increased this to 100 characters to take better advantage of modern widescreen displays.

Before:

After:

Prettier does a lot more to help keep a consistent style:

  • Adds semicolons
  • Consistent quotation usage
  • Consistent trailing commas
  • Consistent spacing between function/method declaration and parameters
  • Consistent spacing for indentation (usually four or two spaces/tabs)
  • Consistent spacing around items within brackets

That’s a lot of things it does, and this isn’t even the complete list. However, as great as Prettier is, computers are dumb and need to explicitly know what to do, whereas our code is full of context and implicit information. While Prettier itself will do a great job, if we tweak our own coding style just a tiny bit, we can help take it to the next level.

Beyond Auto-Formatters

Auto-formatters for our code are a great starting point for a well-styled and intuitive way to understand codebases. However, we developers can go one step further by developing good habits to use in conjunction with our auto-formatter to further improve our intent within our code. These are a bit more subjective, but hopefully easy enough to understand and integrate into your workflow.

Grouping Logical Blocks

This involves the use of line breaks to group your lines of code together into smaller, logically related blocks of code. Now, what do we mean when we say logically grouped? This can be quite subjective and there’s no correct answer here, but I regard this as lines of code that are (roughly) working on the same thing.

Let’s say, for example, that we’re setting a large number of fields on a Contact record – we could consider all the mailing address fields as a logical block. This can also be applied to instance variables, grouping those likely to be worked on together or with a similar theme.

Line Breaks Before Control Flow Statements

First off, let’s define control flow statements (any of the following):

  • If/else statements
  • Switch statements
  • Do while loops
  • While loops
  • For loops
  • Break statements
  • Continue statements
  • Return statements

We can also include the following exception flow statements in this rule:

  • Throw statements
  • Try/Catch/Finally blocks

All of the statements above are used to define conditional blocks of code, or to control the flow through them. Since these statements have huge impacts on how our code behaves, clearly indicating this to a read is paramount for readability. We do this simply by introducing line breaks before these statements, however, we avoid a line break before these statements if they are the first line of code within their block.

Always Use {Curly Braces}

This is a pretty clear-cut rule. Always use curly braces when you can. This means no one-liner “if” statements or “for” loops. This rule isn’t just about improving readability, it’s also about reducing the likelihood of bugs occurring due to missing braces – a more common and potentially dangerous scenario than one might expect!

Summary

Despite its apparent simplicity, code formatting is one of the most important aspects of a codebase. A lack of standardization can quickly lead to difficult-to-maintain and bug-prone code, simply because it can be difficult for developers to understand original intent, or simply what’s really happening within a section of code.

Code formatting standards help alleviate these issues by introducing company-wide policies for how our code should look. This helps us to onboard new developers more efficiently and reduces developer frustrations when working on older pieces of code.

Since “what’s best” can be a highly subjective matter (and will almost certainly lead to disagreements), adopting an opinionated code formatter such as Prettier can be a quick and painless way to roll out standardizations across any number of developers – all without hurting people’s feelings about whose style is best!

The Author

Alex Crisp

Alex is CTO for Seven20, an ISV providing a CRM/ATS built on Salesforce. He has a wealth of experience building everything and anything on the Salesforce platform.

Comments:

    Benjamin Pirih
    October 27, 2022 9:26 pm
    Great article! As someone who has seen many codebases and lost a bit of hair on my head in the process.. Having a consistent formatting methodology is extremely important! Have worked in orgs where I could look at the code and tell which developer has written a chunk of code based on how it is formatted. This is horrible as it silos the code and prevents everyone from sharing responsibility over the entire codebase. Moreover poorly formatted code tends to hide problems. Hence a code that has a bad scent is often poorly formatted and hides issues or hasn't been peer reviewed. Using an automated tool reduces the need to pound through these methodologies in code reviews and allows team to instead focus on what the code is doing instead of how it is formatted. This is all great stuff!
    Mariyan
    October 28, 2022 5:36 pm
    When I see "list.isEmpty() == false", something happens with my heart.
    Alex Crisp
    October 31, 2022 4:57 pm
    Hey Mariyan, In this situation we are using "list?.isEmpty() == false" - the safe navigator operator. This allows the check to support null lists without throwing a null pointer exception, pretty useful in some situations!

Leave a Reply