Good Code
The good version treats incoming data as untrusted and returns a clear failure before the rest of the code touches nested fields.
Lesson 03
Check data from outside your code before the rest of the function trusts it.
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"),
},
};
}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()),
},
};
}The good version treats incoming data as untrusted and returns a clear failure before the rest of the code touches nested fields.
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.