Best practice with big classes Apex

We’ve got this recommendation from Salesforce after an audit

Class Complexity:

• Refactor complex classes and methods into more manageable classes. Consider the use of Process Builder to move piece of code that can be built with Process Builder.

• Best Practice:

  • Classes < 400 lines

  • Methods < 100 lines

I wonder if does this have anything to do with performance or something else other than the readability of the code ?

Answer

There are a couple of non-readability considerations. The primary reasons are for legibility, though. Once you’re nearing 100 lines of code, that means that you have to keep track of 4 pages worth of code in your head. This isn’t particularly practical, as our brains simply don’t work that way. I usually limit my methods to 1-2 pages (25-50 lines of code).

One rare limitation you have probably never seen is that methods are limited to 65,536 bytes of compiled bytecode. In practice, any method that is nearing this limit will probably be impossible to debug accurately, and is probably at risk of throwing CPU or heap governor limits. That said, there is still a hard limit on the size of each method. A related limitation is that the stack is limited to 1000 method entries. This is pretty hard to reach in normal cases, but be aware of using recursion-based methods. For example, if you wrote the following method:

public Integer sumDivergent(Integer total) {
    return total > 0? sumDivergent(total-1) + total: total;
}

subDivergent(5) would be 15, but sumDivergent(1000) would be an exception. In this case, you’d have to write it as a loop:

public Integer subDivergent(Integer total) {
    Integer result = 0;
    while(total-->0) {
        result += total;
    }
    return result;
}

Second, all of your code is being frequently compiled as it is invalidated from the two cache systems that are in place. This invalidation occurs, for example, when a related class is changed, or certain types of metadata are modified. Once invalidated, the system waits until the next time the class needs to run before compiling the code again, which means, for example, a Visualforce page will take unusually long load, or a record might take longer saving. Having your code be as concise as possible will reduce these periodic startup issues.

Attribution
Source : Link , Question Author : benahm , Answer Author : sfdcfox

Leave a Comment