# Code Smell 160 - Invalid Id = 9999

> TL;DR: Don't couple real IDs with invalid ones. In fact: Avoid IDs.

# Problems

- [Bijection](https://maximilianocontieri.com/the-one-and-only-software-design-principle) violation

- You might reach the invalid ID sooner than your think

- Don't use [nulls](https://maximilianocontieri.com/null-the-billion-dollar-mistake) for invalid IDs either

- Coupling flags from caller to functions

# Solutions

1.  Model special cases with special objects.

2. Avoid 9999, -1, and 0 since they are valid domain objects and implementation coupling.

3. Introduce Null Object

# Context

In the early days of computing, data types were strict. 

Then we invented [The billion-dollar mistake](https://maximilianocontieri.com/null-the-billion-dollar-mistake).

Then we grew up and model special scenarios with polymorphic special values.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/342599869ca032390b55d4cc76c49548)
```c
#include "stdio.h"
#include "stdlib.h"
#include "stdbool.h"
#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)
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/40fb4a5238c9d6fbf5ad0f0aefa7fd07)
```c
#include "stdio.h"
#include "stdlib.h"
#include "stdbool.h"
// No INVALID_VALUE defined

int main(void)
{    
    int id;
    id = get_value();
    if (!id) 
    { 
        return EXIT_FAILURE;
        // Sadly, C Programming Language has no exceptions
    }  
    return id;
}  

get_value() 
{
  // something bad happened
  return false;
}

// returns EXIT_FAILURE (1)
```

# Detection

[X] Semi-Automatic 

We can check for special constants and special values on the code.

# Tags

- Null

# Conclusion

We should use numbers to relate to the external identifiers. 

If no external identifier exists, then it is not a number.

# Relations

%[https://maximilianocontieri.com/code-smell-120-sequential-ids]

%[https://maximilianocontieri.com/code-smell-12-null]

# More Info

%[https://maximilianocontieri.com/null-the-billion-dollar-mistake]

%[https://maximilianocontieri.com/y2k22-the-mistake-that-embarrasses-us]

# Disclaimer

Code Smells are just my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).

# Credits

Photo by [Markus Spiske](https://unsplash.com/@markusspiske) on [Unsplash](https://unsplash.com/s/photos/flag-number)  

* * *

> Bugs lurk in corners and congregate at boundaries.

_Boris Beizer_
 
%[https://maximilianocontieri.com/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
