Skip to content

Instantly share code, notes, and snippets.

@pmn4
Created August 23, 2017 14:34
Show Gist options
  • Save pmn4/a3b187bc85a717b33a55b5c138702d7c to your computer and use it in GitHub Desktop.
Save pmn4/a3b187bc85a717b33a55b5c138702d7c to your computer and use it in GitHub Desktop.
Breaking complex conditional statements into more a readable/commentable form yields Code Climate warnings.
// to increase readability and to allow for more sane and detailed
// commenting, I prefer to break up complex conditional statements
// into separate statements in a separate function, using `return`
// to short-circuit when a condition has failed
/////////////////////////////////////////////////////////////////
// as an alternative to combining the condition and the behavior:
// ❌❌❌
function render() {
if (
Flags.isEnabled("feature") &&
!Page.isCheckout() &&
!TrafficSource.isPaid() &&
!this.isDisabled() &&
Experiments.getTreatment("feature") !== "control"
) {
// continue rendering
}
}
// ❌❌❌
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
// I prefer to split the conditions up in a new method:
// ✅✅✅
function isEligibleForFeature() {
// check for the feature flag
if (!Flags.isEnabled("feature")) { return false; }
// never interrupt the checkout funnel
if (Page.isCheckout()) { return false; }
// do not show to paid traffic, where bounce rate is high
if (TrafficSource.isPaid()) { return false; }
// has the user dismissed this feature already?
if (this.isDisabled()) { return false; }
// ⚠️ Code Climate warns about too many return statements here
// do not show to users in the experiment group
if (Experiments.getTreatment("feature") === "control") { return; }
return true;
}
function render() {
if (!this.isEligibleForFeature()) { return; }
// continue rendering...
}
// ✅✅✅
/////////////////////////////////////////////////////////////////
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment