Efficient Apex: Context is not an excuse for using bad names

💡
This is an exclusive preview of chapter 2 of my upcoming book Efficient Apex.

Context

Sometimes, no matter how well we name our programming constructs, they don’t make sense to outsiders or new developers. More often than not, you need context to understand why particular name or terminology is being used. Context is not an excuse to use poorly thought-out names though.

The problem

When I was discussing this book with another Salesforce developer, they showed me some of their open-source work. In one of their projects, I found this Apex class:

public with sharing class File_t extends DomainBuilder {

    public File_t() {
    
            super(ContentVersion.SObjectType);
            name('file');
            path('/document.pdf');
            body('content');
    }

    public File_t name(String value) {
            return (File_t) set(ContentVersion.Title, value);
    }
...

The first time I saw this, my immediate reaction was: “What does that _t stand for in the class name? Does it mean ‘test’? ‘type’? or ‘Tom’?” There was no way for me to know. I decided to ignore this and kept inspecting the rest of the code, but my brain wouldn’t let it go. Every few seconds, I would start thinking what kind of mysterious context I must be missing. Surely that _t represents something important!

So I discussed this with the developer, and they explained to me that with this Domain Builder library you can create classes that represent custom objects. For example, if you have a custom object called Product_Master__c ,then you could create a corresponding class called ProductMaster.cls . However, you can’t create an Apex class with the name of a standard object, such as Account.cls or Opportunity.cls , or in this case, File ,because those are the names of standard objects and are reserved.

Their solution was to append the letter t to those classes, which stands for “test”. How could I have known this? There was nothing in the code that would imply that t stood for “test”. The only way I could know this was by speaking to them, and that conversation provided the context that I needed.

A better way

Still, relying solely on context is not good idea. We must ensure our Apex construct names are clear and unambiguous.

You missed the best part 😔. Join the community of 70+ paid subscribers who are embracing a software engineering mindset and benefiting from this exclusive content. Don't be left behind—stand out from the crowd!

Subscribe for exclusive Salesforce Engineering tips, expert DevOps content, and previews from my book 'Clean Apex Code' – by the creator of HappySoup.io!
fullstackdev@pro.com
Subscribe