# Code Smell 192 - Optional Attributes

> TL;DR: Collections are fantastic. And Polymorphic.

# Problems

- [Null](https://maximilianocontieri.com/null-the-billion-dollar-mistake)
- If Pollution 

# Solutions

1. Change the optional attribute to a collection.

# Context

If you need to model something that might be missing, some fancy languages will provide optional, nullable, and many other wrong solutions dealing with [The Billion Dollar Mistake](https://maximilianocontieri.com/null-the-billion-dollar-mistake).

Empty collections and non-empty collections are polymorphic.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/a6549bd6a333574a2ba7120a74bcb974)
```javascript
class Person {
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }
  
  email() {
    return this.email;
    // might be null    
  }
  
}

// We cannot use safely person.email()
// We need to check for null explicitly
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/ec3cca15f071ae1ecebb223675e0cf79)
```javascript
class Person {
  constructor(name, emails) {
    this.name = name;
    this.emails = emails;
  }
    
  emails() {
    return this.emails;
  }
  
  // We can mutate the emails since they are not essential
  
  addEmail(email) {
    this.emails.push(email);
  }
  
  removeEmail(email) {
    const index = this.emails.indexOf(email);
    if (index !== -1) {
      this.emails.splice(index, 1);
    }
  }
}

// we can iterate the person.emails() 
// in a loop without checking for null 
```

# Detection

[X] Semi-Automatic 

You can detect nullable attributes and change them when necessary.

# Tags

- Null 

# Conclusion

This is a generalization of the null object pattern.

# Relations

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

%[https://maximilianocontieri.com/code-smell-149-optional-chaining]

%[https://maximilianocontieri.com/code-smell-19-optional-arguments]

# More Info

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

- [Null Object Pattern](https://en.wikipedia.org/wiki/Null_object_pattern)

# 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 [Levi Jones](https://unsplash.com/@levidjones) on [Unsplash](https://unsplash.com/photos/n0CTq0rroso)
  
* * *

> To iterate is human, to recurse divine

_Peter Deutsch_
 
%[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]
