Javier Arroyo
Mega Guru

This article is Day 1 of a multi-post series about refactoring Code Smells. Code Smells are characteristics that can negatively impact code; ranging from hindered read-ability, clutter, unscale-able, even outdated programming practices.

Refactoring practices will be mostly, if not all, from the Imperative/OO perspective as ServiceNow OOTB code is all written as such. I will try to be brief and attempt to use language features specific to JavaScript that may differ from those used by classically trained coders.

Day 1 - refactoring comments.

The strategy is straightforward: extract code into a function, replace the code with that function call and delete comments.

Why are comments a smelly?

  • Tasks the reader by having to read the comments, still decipher the code, then analyze if both match
  • Will grow overtime leading to bloating
  • Must be kept up-to-date
  • Increase code surface thereby chances for bugs
  • Comments belong atop the function not on the inside. Better served for public facing APIs.
  • Deodorize problems in design that should be improved
  • Can indicate too much responsibility in a function

Sometimes comments are a must, those times can be said to be when a piece of code was handled in some sort of special case for which context makes a difference. The author then comments what will be of paramount importance for future readers that isn't visible by reading the code. Cryptic code isn't commented, it's rewritten.

Example:

while (license.next()) {
    licensedCompany = license.company.getValue();
    licenses.push(licensedCompany);
}​
var au = ArrayUtil();
//sys_id of comapnies for which licenses does not already exist
var createCompanyLicense = au.diff(licenses, excistingLicenses); 

Solution: 
Extract code into a function, call the function in place of extracted code, delete comments

1. New Function

function getMissingCompayLicenses (companyLicenses, allLicenses) {
     return new ArrayUtil().diff(companyLicenses, allLicenses);

}

2. Calling the function

while (license.next()) {
    licensedCompany = license.company.getValue();
    licenses.push(licensedCompany);
}​

var missingLicenses = getMissingCompanyLicenses(licenses, existingLicenses);

The result is idiomatic expressions. Reduce mental capacity by not having to interpret code.

 

Version history
Last update:
‎02-24-2020 05:29 PM
Updated by: