DEV Community

Cover image for Code Smell 210 - Dynamic Properties
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

Code Smell 210 - Dynamic Properties

Laziness and magic bring defects

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

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"
Enter fullscreen mode Exit fullscreen mode

Right

class Dream:
    def __init__(self):
        self.presentation = None

nightmare = Dream()

nightmare.presentation = "I am the Sandman"

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

Enter fullscreen mode Exit fullscreen mode

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 which is another smell.

Relations

Disclaimer

Code Smells are my opinion.

Credits

Photo by Karsten Würth on Unsplash


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


This article is part of the CodeSmell Series.

Top comments (0)