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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay