# Code Smell 210 - Dynamic Properties

> TL;DR: Be explicit with your attributes

# Problems

- Readability

- Scope definition

- Unnoticed typos

# Solutions

1. Favor languages forbidding dynamic properties

# Context

Dynamic properties break type safety since it's easy to introduce typos or use the wrong property names accidentally. 

This can lead to runtime errors that can be difficult to debug, especially in larger codebases.

They also hide possible name collisions since dynamic properties may have the same name as properties defined in the class or object, leading to conflicts or unexpected behavior.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/1fceddaa27b7dcbb2cf0ba4f85861237)
```python
class Dream:
    pass

nightmare = Dream()

nightmare.presentation = "I am the Sandman"
# Presentation is not defined
# It is a dynamic property

print(nightmare.presentation) 
# Output: "I am the Sandman"
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/b2f04e4bafd415006b4ace96e4456612)
```python
class Dream:
    def __init__(self):
        self.presentation = None

nightmare = Dream()

nightmare.presentation = "I am the Sandman"

print(nightmare.presentation) 
# Output: "I am the Sandman"

```

# Detection

[X] Automatic 

Most languages have compiler options to avoid them.

# Tags

- Metaprogramming

# Conclusion

Dynamic properties are supported in many programming languages like PHP,    Python, Ruby,  JavaScript,  C#, Objective-C, Swift, Kotlin, etc.

In these languages, dynamic properties can be added to objects at runtime, and accessed using the object's property accessor syntax. 

Bear in mind that having public attributes favors [Anemic Objects](https://maximilianocontieri.com/code-smell-01-anemic-models) which is another smell.

# Relations

%[https://maximilianocontieri.com/code-smell-109-automatic-properties]

%[https://maximilianocontieri.com/code-smell-01-anemic-models]

# Disclaimer

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

# Credits

Photo by [Karsten Würth](https://unsplash.com/@karsten_wuerth) on [Unsplash](https://unsplash.com/photos/0w-uTa0Xz7w)
    
* * *

> It's easy to cry "bug" when the truth is that you've got a complex system and sometimes it takes a while to get all the components to co-exist peacefully.

_D. Vargas_
 
%[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]
