Skip to content

Instantly share code, notes, and snippets.

@nicograef
Last active June 30, 2020 09:30
Show Gist options
  • Save nicograef/c30c73d53cbb26ecf7c10ea3d3366050 to your computer and use it in GitHub Desktop.
Save nicograef/c30c73d53cbb26ecf7c10ea3d3366050 to your computer and use it in GitHub Desktop.

These guidelines are supposed to improve code quality and readability.

Naming Stuff

// - don't
const cid = 13;

// + do
const customerId = 13; // or customerID
// - don't
function compare(a, b) {
  return a.weight - b.weight > 0 ? 1 : -1;
}

// + do
function comparePersonsByWeight(person1, person2) {
  if (person1.weight > person2.weight) return 1;
  else if (person1.weight === person2.weight) return 0;
  else return -1;
}
// - don't
onSearchTermChange(val) {
    this.searchTerm = val
}

// + do
onSearchTermChange(newSearchTerm) {
    this.searchTerm = newSearchTerm
}
// - don't
genericSurveyService.getChangeStream().then((x) => {
  this._subscription = x.subscribe(this.handleGenericSurveyUpdates.bind(this));
});

// + do
genericSurveyService.getChangeStream().then((changeStream) => {
  this._changeStreamSubscription = changeStream.subscribe((newGenericSurveys) =>
    this.handleGenericSurveyUpdates(newGenericSurveys)
  );
});

Function Return Values

// - don't
let myValues = getSomeRawValues();
processInPlace(myValues);
return myValues.map((x) => x.toString());

// + do
const myRawValues = getSomeRawValues();
const myProcessedValues = processWithReturn(myRawValues);
const myValues = myProcessedValues.map((x) => x.toString());
return myValues;

All in One

// - don't
return !this.valueIsEmail
    ? true
    : value === '' || pattern.test(value) || (this.$i18n.t('patient_merge_dialog.rules_email_invalid') as string);

// + do
if (!this.valueIsEmail) return true;

const isEmptyEmail = value === '';
const isInvalidEmail = pattern.test(value);

if (isEmptyEmail || isInvalidEmail) return true;

const invalidEmailMessage = this.$i18n.t('patient_merge_dialog.rules_email_invalid') as string
else return invalidEmailMessage;

// fyi: this code is not understandable to me

Line Spacing

// - don't
const someValue = giveMeValue()
otherStuff().then(res => {
    if (res.err) console.log(err);
    const re2 = doSomething(res)
    return res2.result.map(x => y)
})

// + do
const someValue = giveMeValue()

otherStuff().then(res => {
    if (res.err) console.log(err);

    const re2 = doSomething(res)
    const mappedResult = res2.result.map(x => y)

    return mappedResult
})

Conditions and Early Returns

// - don't
if (someValue && someValue !== "not this" && someValue !== "not that") {
  dostuff();
} else return;

// + do
if (!someValue) return;
doStuff();

// + or do
if (!someValue) throw new Error("Please provide a value");
dostuff();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment