2

I've been writing a lot of time related code recently, and in various files, I always end up re-defining things like

var SECOND = 1000; var MINUTE = 60 * SECOND;

This gets frustrating quickly. So I'm considering two possibilities:

  1. Getting rid of the constants and instead letting things be inferred from code like 60 * 1000
    • I dislike this option because it's not as human readable
  2. Attaching the constants to a global so they only have to be written in one place
    • I think this is the best way to go, but I'm unsure about the potential consequences of this
  3. I could use a package and import from it
    • This has the same problem that I'm already doing, which would be defining it everywhere over and over

How do you handle this issue or is it something we have to live with?

Side note 1: I am writing this in JavaScript, which is why globals are an option, but I feel like this might still be applicable to other languages

Side note 2: Specifically for JavaScript, why are these constants not already attached to the global objects browser/globals?

8
  • 3
    Possible duplicate of Eliminating Magic Numbers: When is it time to say "No"?
    – gnat
    Commented Jan 24, 2017 at 17:18
  • 3
    What's wrong with using Javascript Date objects?
    – Erik Eidt
    Commented Jan 24, 2017 at 18:23
  • 1
    Be careful with using constants for time like this. Not every minute has 60 seconds.
    – zzzzBov
    Commented Jan 24, 2017 at 19:22
  • 1
    C# for example has a TimeSpan which encapsulates the unit and the value. For JavaScript, perhaps checkout the moment.js library, which is useful for managing time.
    – Matthew
    Commented Jan 24, 2017 at 20:21
  • @ErikEidt I'm using this for things like setTimeout(someFunction, 10 * SECOND), so Date objects won't work for that. Same answer applies to using moment, @Matthew, which I am using for other functionality, but it does not have constants Commented Jan 24, 2017 at 21:10

1 Answer 1

1

I don't handle constants like that if I can avoid it.

Using the specific example of time in JS, I would use a library that handles those unit conversions itself. Instead of setTimeout(someFunction, 10 * SECOND), I would use something akin to setTimeout(someFunction, moment.duration({ seconds: 10 }).asMilliseconds())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.