JavaScript

Lesson 03

Validating data boundaries

Check data from outside your code before the rest of the function trusts it.

Good Code

review-payload.js
function normalizeReviewPayload(payload) {
  // Validate the boundary before reading nested fields.
  if (!payload || typeof payload !== "object") {
    return { ok: false, error: "Invalid payload." };
  }

  const { title, reviewers } = payload;

  if (typeof title !== "string" || title.trim() === "") {
    return { ok: false, error: "Title is required." };
  }

  if (!Array.isArray(reviewers)) {
    return { ok: false, error: "Reviewers must be a list." };
  }

  return {
    ok: true,
    value: {
      title: title.trim(),
      reviewers: reviewers.filter((id) => typeof id === "string"),
    },
  };
}

Bad Code

review-payload.js
function normalizeReviewPayload(payload) {
  // This trusts external shape before proving it exists.
  return {
    ok: true,
    value: {
      title: payload.title.trim(),
      reviewers: payload.reviewers.map((id) => id.toLowerCase()),
    },
  };
}

Review Notes

What to review

Good Code

The good version treats incoming data as untrusted and returns a clear failure before the rest of the code touches nested fields.

Bad Code

The bad version is short, but it crashes when the payload shape changes or when a field is missing, which turns a data problem into an unrelated runtime error.

Takeaways

  • Validate API, storage, and message payloads at the boundary before using nested fields.