Why does this implementation violate both DRY and KISS principles?
class UserValidator {
validateUsername(username) {
if (username.length < 3) return 'Username too short';
if (username.length > 20) return 'Username too long';
if (!/^[a-zA-Z0-9_]+$/.test(username)) return 'Invalid characters';
return null;
}
validatePassword(password) {
if (password.length < 3) return 'Password too short';
if (password.length > 20) return 'Password too long';
if (!/^[a-zA-Z0-9_]+$/.test(password)) return 'Invalid characters';
return null;
}
}
This code violates both DRY and KISS principles in several ways:
1. DRY violation: The length validation and character validation logic is duplicated between methods
2. KISS violation: The validation logic could be simplified using a more generic approach
A better implementation would be:
class UserValidator {
validateField(value, field) {
const validations = {
length: { min: 3, max: 20 },
pattern: /^[a-zA-Z0-9_]+$/
};
if (value.length < validations.length.min) return `${field} too short`;
if (value.length > validations.length.max) return `${field} too long`;
if (!validations.pattern.test(value)) return 'Invalid characters';
return null;
}
}