Clean code with Functional Validator Pipeline

When facing many requirement changes or as an application keeps growing, validation logic can become a real nightmare.

Validating data is a simple job that most programmers do every day. However, when facing many requirement changes or as an application keeps growing, validation logic can become a real nightmare. This post proposes a way to organize validation logic as cleanly as possible, making it more readable, maintainable and reusable.

Below is an example of validation code at the very beginning. The validation rules are simple, with only a few properties to check. Here, all data runs through this function (passed in as the function argument) to be validated.

function validatorIsHocSinhGioi(obj) {
  if (obj.score < 8) {
    alert("Score below 8, how can you be an excellent student");
    return false;
  } else if (obj.ethics < 8) {
    alert("Even with good conduct you still can't be an excellent student");
    return false;
  } else {
    return true;
  }
}

Since the validation above doesn’t contain much logic, it looks fine. However, once more conditions get added, the code will definitely need refactoring.

A simple way to make validation code more maintainable is to split up the functions, breaking complex validate functions into smaller ones. One function combines these small pieces of validation logic, and when the logic needs to change, you only edit the small function inside.

In the example below, we check whether a student is an excellent student with a function like this:

function checkHocSinhGioi({ obj, errorArray = [] }) {
  if (obj.score > 8 && obj.ethics > 8) {
    return {
      obj,
      errorArray,
    };
  }

  return {
    obj,
    errorArray: [...errorArray, "Does not qualify as an excellent student"],
  };
}

The function above takes two parameters: an object to validate and an array. This array holds all the errors that occur while running the validation checks. This way, if validation fails, the UI can iterate over this array to create a message for each error. Validation passes when errorArray.length === 0, or more briefly !errorArray.length.

Ok, so above we have 1 validation rule. How do we combine multiple validation rules? If you’re using Lodash, you can use the pipe() function right away, which lets you combine multiple functions together (like pipes connected one after another).

If you’re not using Lodash, you can create your own pipe function with the following code:

const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);

To describe more clearly how to combine multiple validation rules with the pipe function, we need a few more rules (each function contains only one piece of validation logic). Suppose we have two more validation rules like this:

function checkHocSinhDiHocDayDu({ obj, errorArray = [] }) {
  if (obj.absent === 0) {
    return {
      obj,
      errorArray,
    };
  }

  return {
    obj,
    errorArray: [...errorArray, "This student does not attend school regularly"],
  };
}

function checkHocSinhBiGhiSoDauBai({ obj, errorArray = [] }) {
  if (obj.frauds && !obj.frauds.length) {
    return {
      obj,
      errorArray,
    };
  }

  return {
    obj,
    errorArray: [...errorArray, "This student has been written up in the class logbook."],
  };
}

The pipe function works by taking the return value of the previous function and passing it as the argument of the next one, in other words it creates a pipeline of functions. Implemented in code, it looks like this:

const hocSinhXuatSacValidator = pipe(
  checkHocSinhGioi,
  checkHocSinhDiHocDayDu,
  checkHocSinhBiGhiSoDauBai
);

To check for errors after running the pipe function, see the complete code below:

// Create the validation pipeline
const hocSinhXuatSacValidator = pipe(
  checkHocSinhGioi,
  checkHocSinhDiHocDayDu,
  checkHocSinhBiGhiSoDauBai
);

// The obj to validate
const hocSinh = {
  name: "Phạm Hoàng Linh",
  score: 6,
  ethics: 5,
  absent: 2,
  frauds: ["Talked back to the teacher", "Interrupted the teacher"],
};

// Run the validation pipeline
const { errorArray } = hocSinhXuatSacValidator(hocSinh);

// Check for errors and display them
if (!errorArray.length) {
  // Passed validation
  capGiayChungNhanHocSinhXuatSac(hocSinh);
} else {
  // Show errors on the UI
  errorArray.forEach(error => {
    alert(error);
  });
}

Conclusion

After organizing the validation logic as a functional pipeline, the code is clearly much more readable and maintainable. It also makes organizing the codebase easier and cleaner, and you can create a separate module dedicated to holding the validate functions.