Skip to content

Instantly share code, notes, and snippets.

@im4aLL
Last active April 4, 2024 16:37
Show Gist options
  • Save im4aLL/fba2c20bdbdfa4b52b710b6f6401272b to your computer and use it in GitHub Desktop.
Save im4aLL/fba2c20bdbdfa4b52b710b6f6401272b to your computer and use it in GitHub Desktop.
Guard Clause
// Guard Clause is a technique derived from the fail-fast method
// whose purpose is to validate a condition and immediately stop the code execution
// about the result of the validation.
// Using guard clauses is a common and clean technique for simplifying the code block and avoiding unnecessary complexity.
// Example 1
const submitForm = (formData, formMeta) => {
if (!formMeta.hasError(formData)) {
formData.submit();
}
}
const submitFormWithGuardClause = (formData, formMeta) => {
if (formMeta.hasError(formData)) {
return;
}
formData.submit();
}
// Example 2
if (hasSubscription) {
if (email === contact.email) {
const isUpdated = this.db
.where('email', $email)
.where('is_subscribed', !isSubscribed)
.update({
'is_subscribed': isSubscribed,
});
if (isUpdated) {
if (hasSubscription) {
event(new Subscribed(email));
} else {
event(new Unsubscribed(email));
}
}
}
}
// with guard clause
if (!hasSubscription) {
return;
}
if (email !== contact.email) {
return;
}
const isUpdated = this.db
.where('email', $email)
.where('is_subscribed', !isSubscribed)
.update({
'is_subscribed': isSubscribed,
});
if (!isUpdated) {
return;
}
const instance = hasSubscription ? new Subscribed(email) : new Unsubscribed(email);
event(instance);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment