Last active
October 26, 2024 01:36
-
-
Save nsdevaraj/7c49ba167452b3b81e0e70705319a1f1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example with nested conditionals (harder to read) | |
function processUserRegistration(user) { | |
if (user.hasValidEmail) { | |
if (user.isMinimumAge) { | |
if (user.hasAcceptedTerms) { | |
if (user.hasProvidedValidPassword) { | |
// Perform registration | |
return { | |
success: true, | |
userId: generateUserId(), | |
message: 'Registration successful!' | |
}; | |
} else { | |
return { | |
success: false, | |
message: 'Password requirements not met' | |
}; | |
} | |
} else { | |
return { | |
success: false, | |
message: 'Terms must be accepted' | |
}; | |
} | |
} else { | |
return { | |
success: false, | |
message: 'Must be at least 18 years old' | |
}; | |
} | |
} else { | |
return { | |
success: false, | |
message: 'Invalid email address' | |
}; | |
} | |
} | |
// Same logic using guard clauses (cleaner and more maintainable) | |
function processUserRegistrationWithGuards(user) { | |
if (!user.hasValidEmail) { | |
return { | |
success: false, | |
message: 'Invalid email address' | |
}; | |
} | |
if (!user.isMinimumAge) { | |
return { | |
success: false, | |
message: 'Must be at least 18 years old' | |
}; | |
} | |
if (!user.hasAcceptedTerms) { | |
return { | |
success: false, | |
message: 'Terms must be accepted' | |
}; | |
} | |
if (!user.hasProvidedValidPassword) { | |
return { | |
success: false, | |
message: 'Password requirements not met' | |
}; | |
} | |
// All validations passed, perform registration | |
return { | |
success: true, | |
userId: generateUserId(), | |
message: 'Registration successful!' | |
}; | |
} | |
// Helper function | |
function generateUserId() { | |
return Math.random().toString(36).substr(2, 9); | |
} | |
// Example usage: | |
const user = { | |
hasValidEmail: true, | |
isMinimumAge: true, | |
hasAcceptedTerms: false, | |
hasProvidedValidPassword: true | |
}; | |
console.log(processUserRegistration(user)); | |
console.log(processUserRegistrationWithGuards(user)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment