cover-img

Code Smell 39 - new Date()

26 December, 2022

4

4

0

70s first tutorial: getCurrentDate(). Piece of Cake. We are in the 20s Time is global no more

Problems

Coupling

Fragile Tests

Timezone Problems

Solutions

1.

Use Dependency injection to decouple time source.

Sample Code

Wrong

Right

Detection

We should forbid global functions policies. We need to couple to accidental and pluggable time sources.

Tags

Globals

Conclusion

Date.today() , Time.now(), and other global system calls are coupling smell.
Since tests must be in full environmental control. We should easily set up time, moved it back and forth etc.
Date and Time classes should only create immutable instances. It is not their responsibility to give the actual time. This violates Single Responsibility Principle.
The passage of time is always scorned by programmers. This makes objects mutable and designs poor and coupled.

Relations

More Info

In programming, the hard part isn't solving problems, but deciding what problems to solve.

Paul Graham
This article is part of the CodeSmell Series.

4

4

0

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.