Code Quality

sea 5


Introduction

There is no such thing as "perfect" code — there is only better code!

Instead of seeking perfection, we should seek for is "continuous improvement"...

We rarely write tests for our tests — a human must ensure that tests are valid.

  • Code Quality Is Everyone’s Responsibility including:

    • Developer
    • Tester
  • Code quality aspects

AspectComments
ReliabilityProbability that a system will run without failure over a specific period of operation
MaintainabilityHow easily software can be maintained
Testabilityhow well the software supports testing efforts
Portabilityhow usable the same software is in different environments
Reusabilitywhether existing assets — such as code — can be used again
  • Code quality Metrics
MetricComments
Defect MetricsNumber of defects — and severity of those defects — are important metrics of overall quality.
Complexity MetricsCyclomatic complexity for example
Testabilityhow well the software supports testing efforts
Portabilityhow usable the same software is in different environments
  • Ways to Improve Code Quality
WayComments
Use a coding standardMakes everyone to use the right style
Analyze code — before code reviewsAnalyze code as soon as it’s written
Follow code review best practicesManual code reviews are still important for verifying the intent of the code
Refactor legacy code (when necessary)help you clean up your codebase and lower its complexity

Write Maintainable Testable Good Code

  • readable
  • understandable
  • testable
Good Code
Does what it should
Follows a consistent style
It is easy to understand
Has been well-documented
It can be tested
Key Points
Avoid Code with global, mutable state - that any code can access, and any code can modify
A class should ask for its dependencies through its constructor rather than acquiring them itself - dependency injection
Optimize the code for the reader of the code, not the writer - Good Code Is Easily Read and Understood, in Part and in Whole
DRY - Don't repeat yourself - it is easier to maintain the code if it only exists in one place
Do the simplest, smallest thing you can do to add some value

Static Code Analysis

  • Run Static Code Analysis tools like PMD that attempt to highlight possible violations and vulnerabilities within ‘static’ (non-running) source code by using techniques such as Taint Analysis and Data Flow Analysis

  • Integrated with IDEs like VSCode, VSCode Apex PMD

Demo of PMD VScode Extn

New PMD report

Demo (will be part of PMD 6.50.0)

PMD Report

Screenshot

PMD Report Screenshot

ESLint

ESLinting

  • ESLint in LWC!

Lightning Lint Service

Inclusive Language

Code Review

  • Peer Code Review
    • Individual programmers are less than 50% efficient at finding bugs in their own software.
  • Code Walk-thru
Goals
The overall code health of code base is improving over time
The codebase stays consistent, maintainable
  • What to look for in a Code Review?

    • The developers should test code well-enough that they work correctly by the time they get to code review.
ItemComments
DesignInteractions in the code makes sense?
FunctionalityCode is the manifest of what the developer intended?
ComplexityIs the code is more complex than it should be?. “can’t be understood quickly by code readers.” Over-engineering, where developers have made the code more generic than it needs to be
TestsUnit, integration, or end-to-end tests
NamingDeveloper pick good names for everything?
CommentsDeveloper has written clear comments in understandable Language. Comment should explain why some code exists, and should not be explaining what some code is doing. Regular expressions and complex algorithms often benefit greatly from comments that explain what they’re doing, for example. Note that comments are different from documentation of classes, modules, or functions, which should instead express the purpose of a piece of code, how it should be used, and how it behaves when used
StyleDeveloper follows the published style for a given programming language
DocumentationREADMEs and generated reference docs
  • Code Review Summary
Item
The code is well-designed.
The functionality is good for the users of the code.
Any UI changes are sensible and look good.
Any parallel programming is done safely.
The code isn’t more complex than it needs to be.
The developer isn’t implementing things they might need in the future but don’t know they need now.
Code has appropriate unit tests.
Tests are well-designed.
The developer used clear names for everything.
Comments are clear and useful, and mostly explain why instead of what.
Code is appropriately documented
The code conforms to our style guides

Note to the developers

ItemComments
Don’t Take it PersonallyThe goal of review is to maintain the quality of the codebase and the products
Fix the Code1. Clarify the code 2.code comment that explains why the code is there (if required) 3. Modify the code
Think CollaborativelyIf you disagree with the reviewer, find ways to collaborate: ask for clarifications, discuss pros/cons, and provide explanations of why your method of doing things is better for the codebase

Apex Best Practices

Practice
1. Bulkify your Code
2. Avoid SOQL Queries or DML statements inside FOR Loops
3. Bulkify your Helper Methods
4. Using Collections, Streamlining Queries, and Efficient For Loops
5. Streamlining Multiple Triggers on the Same Object
6. Querying Large Data Sets
7. Use of the Limits Apex Methods to Avoid Hitting Governor Limits
8. Use @future Appropriately
9. Writing Test Methods to Verify Large Datasets
10. Avoid Hardcoding IDs

Naming Conventions

ItemNotesExample
Class NameShould be unique, begin with an Uppercase letter. Do not contain underscores or spaces (except from the prefix and suffix). Should be nouns in mixed cases, with first letter of each interval word capitalizedAccountController
Variable Nameshould be in mixed case (camelCase) with a lowercase first letter. Internal words start with capital lettersgeocodingUrl
Method NameShould be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized - camelCasegetPagedPropertyList(...)
ConstantsClass constants should be all UPPERCASE with words separated by underscoresprivate static final String BASE_URL = 'https://nominatim.openstreetmap.org/search?format=json'
TriggerTrigger, should follow Salesforce Trigger – One trigger per object

Test Driven Development

  • Test Driven Development(TDD) = Test First Development(TFD) + refactoring
  • First write the test code before the functional code.
  • it's a way to get SelfTestingCode

TDD

StepsComments
Write a quick testBasically just enough code to fail
Run the testIt should fail
Write functional codeSo that pass the test
Finally, run the testTo check whether it has passed
Re-factor until tests PASS to continue with further development

LWC Best Practices

SOQL Best Practices

Lightning Performance Best Practices

Large Data Volumes

LWC Test Coverage - Jest

Write Jest tests to:
Test a component in isolation
Test a component’s public API (@api properties and methods, events)
Test basic user interaction (clicks)
Verify the DOM output of a component
Verify that events fire when expected

Simple Jest Demo

Jest Demo

// app.js
function sum(a, b) {
  return a + b;
}
module.exports = sum;
// app.test.js
const sum = require('./app');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

yarn test
yarn test
yarn run v1.22.17
$ jest
 PASS  ./app.test.js
  ✓ adds 1 + 2 to equal 3 (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.519 s, estimated 1 s
Ran all test suites.
✨  Done in 1.76s.

LWC Example (unedited)

LWC jest demo

Using Sa11y for 508 compliance

LWC Jest 508 test

More info

Testing Lightning Web Components

Automated Accessibility Tests with sa11y

Visualizing Code Coverage

LWC i18n

Demo showing how to use Custom Labels for localization

sfdx mohanc:mdapi:ls -u mohan.chinnappan.n.sel@gmail.com -i listCL.json -t CustomLabel 
[ 'Greeting' ]
{
    "fullName": "Greeting",
    "language": "en_US",
    "protected": "true",
    "shortDescription": "Greeting",
    "value": "Hello World From LWC"
}

Resources

Generate

sfdx mohanc:slides:gen -i cq.md -o cq.md.html -t 'Notes on Code Quality'

Page View