DEV Community

Cover image for Code Smell 39 - new Date()
Maxi Contieri
Maxi Contieri

Posted on • Edited on • Originally published at maximilianocontieri.com

2 1

Code Smell 39 - new Date()

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

var today = new Date();
view raw globalDate.js hosted with ❤ by GitHub

Right

var ouagadougou = new Location();
var today = myTimeSource.currentDateIn(ouagadougou);
function testGivenAYearHasPassedAccruedInterestsAre10() {
var mockTime = new MockedDate(new Date(2021, 1, 1));
var domainSystem = new TimeSystem(mockTime);
// ..
mockTime.moveDateTo(new Date(2022, 1, 1));
// … You set up the yearly interest rate
assertEquals(10, domainSystem.accruedInterests());
}
view raw notcoupled.js hosted with ❤ by GitHub

Detection

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

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

Evil Mutants

Tags

  • Globals

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

Paul Graham

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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