Skip to content

re: Writing code for your future self VIEW POST


Difference is that in first case validation will not db.query if username is too long. In second that db.query and other later tests are usuless


True. For the same functionality you would want something like this:

function validateUsername(username) {
  const isLengthValid = validateUsernameLength(username);

  if (!isLengthValid) return false;

  const isAlphanumeric = validateAlphanumeric(username);

  if (!isAlphanumeric) return false;

  const isUsernameTaken = checkUsernameExists(username);

  if (isUsernameTaken) return false;

  return true;

Or even this:

function validateUsername(username) {
  return validateUsernameLength(username)
    && validateAlphanumeric(username)
    && !checkUsernameExists(username);

Which would only run checkUsernameExists if the tests before it pass. But it's somewhat pseudo code anyway. The point of db.query was to show the single responsibility.

code of conduct - report abuse