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 Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay