Maxint is a very good number for an invalid ID. We will never reach it.
TL;DR: Don't couple real IDs with invalid ones. In fact: Avoid IDs.
-
Bijection violation
-
You might reach the invalid ID sooner than your think
-
Don't use nulls for invalid IDs either
-
Coupling flags from caller to functions
-
Model special cases with special objects.
-
Avoid 9999, -1, and 0 since they are valid domain objects and implementation coupling.
-
Introduce Null Object
In the early days of computing, data types were strict.
Then we invented The billion-dollar mistake.
Then we grew up and model special scenarios with polymorphic special values.
#define INVALID_VALUE 999
int main(void)
{
int id = get_value();
if (id == INVALID_VALUE)
{
return EXIT_FAILURE;
// id is a flag and also a valid domain value
}
return id;
}
int get_value()
{
// something bad happened
return INVALID_VALUE;
}
// returns EXIT_FAILURE (1)
int main(void)
{
int id;
id = get_value();
if (id < 0)
{
printf("Error: Failed to obtain value\n");
return EXIT_FAILURE;
}
return id;
}
int get_value()
{
// something bad happened
return -1; // Return a negative value to indicate error
}
// No INVALID_VALUE defined
[X] Semi-Automatic
We can check for special constants and special values on the code.
- Null
We should use numbers to relate to the external identifiers.
If no external identifier exists, then it is not a number.
Code Smell 120 - Sequential IDs
Null: The Billion Dollar Mistake
Y2K22 - The Mistake That Embarrasses Us
Code Smells are just my opinion.
Photo by Markus Spiske on Unsplash
Bugs lurk in corners and congregate at boundaries.
Boris Beizer
Software Engineering Great Quotes
This article is part of the CodeSmell Series.