Skip to content

Instantly share code, notes, and snippets.

@user24
Last active December 14, 2015 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save user24/5111233 to your computer and use it in GitHub Desktop.
Save user24/5111233 to your computer and use it in GitHub Desktop.
Code Clarity by hoisting logic into nicely named variables
// Succinct, does not create strictly unnecessary variables
// but not easy to read
if((a.notes && a.notes.trim() != "") && (b.notes && b.notes.trim() != "")) {
skip = true;
console.log('too many notes - skipping');
}
// Verbose, creates two vars which are not really needed
// but it's instantly clear what the 'if' is doing
var aHasNotes = (a.notes && a.notes.trim() != "");
var bHasNotes = (b.notes && b.notes.trim() != "");
if(aHasNotes && bHasNotes) {
skip = true;
console.log('too many notes - skipping');
}
@omervk
Copy link

omervk commented Mar 7, 2013

Since the conditions are parallel, I usually use newlines to accent that:

if((a.notes && a.notes.trim() != "") &&
   (b.notes && b.notes.trim() != "")) {
    skip = true;
    console.log('too many notes - skipping');
}

@lotsofcode
Copy link

I would probably move the conditions into a method of my object.

MyObject.prototype.hasNotes = function() {
  return this.notes && this.notes.trim() != "";
};

So then my implimentation is simpler to understand.

if (a.hasNotes() && b.hasNotes()) {

I can then re-use this logic elsewhere in the codebase.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment