How does this code violate the DRY principle, and how can it be improved?
function validateUserEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
function validateAdminEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
function validateSubscriberEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
This code violates DRY by duplicating the email validation logic and regex pattern across three functions. A better approach would be to extract the common validation logic into a single reusable function or constant. Example improvement:
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function validateEmail(email) {
return EMAIL_REGEX.test(email);
}
This way, if the validation logic needs to change, it only needs to be updated in one place, reducing the risk of inconsistencies and making the code more maintainable.