Good Code
The good version gives each failure a named enum value. Callers can log a useful reason, map it to a response, or assert it in tests.
Lesson 06
Return named error codes when validation can fail for multiple reasons, so callers can branch without guessing.
enum ReviewStatus {
REVIEW_OK = 0,
REVIEW_EMPTY_TITLE = -1,
REVIEW_SCORE_OUT_OF_RANGE = -2,
};
enum ReviewStatus validate_review(const char *title, int score)
{
// Named result codes tell callers which input failed.
if (title == 0 || title[0] == '\0') {
return REVIEW_EMPTY_TITLE;
}
if (score < 0 || score > 100) {
return REVIEW_SCORE_OUT_OF_RANGE;
}
return REVIEW_OK;
}int validate_review(const char *title, int score)
{
// A single -1 erases which validation failed.
if (title == 0 || title[0] == '\0') {
return -1;
}
if (score < 0 || score > 100) {
return -1;
}
return 0;
}The good version gives each failure a named enum value. Callers can log a useful reason, map it to a response, or assert it in tests.
The bad version returns -1 for every validation failure. Callers must repeat validation logic or show a generic error to the user.