Skip to main content

Command Palette

Search for a command to run...

Code Smell 210 - Dynamic Properties

Laziness and magic bring defects

Updated
2 min read
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

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

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 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.

Code Smells

Part 1 of 50

In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.