Search code examples
oophungarian-notation

How to model a duration in an object oriented way?


I'm dealing with different APIs that use Integers to model duration. Only they can't seem to agree on the units. Sometimes it's seconds and sometimes it's milliseconds.

So far the best way to avoid errors I've been able to find, is to use Hungarian notation: durationInMillis, durationInSeconds and so on.

It makes me wonder if there's not a better, truly OO way of modeling duration? Something that would allow the type system to help me avoid errors where I mistakenly treat a duration in milliseconds as a duration is seconds and vice versa.


Solution

  • Just give each duration a separate class and use milliseconds as the authoritative form used in calculations -- i.e., overload function getMilliSeconds() in both of your classes.

    class Duration
    {
    ...
        virtual const unsigned long long getMilliSeconds() const;
    ...
    }
    
    class MilliSeconds : public Duration
    {
    ...
    };
    
    class Seconds : public Duration
    {
    ...
    };
    

    Allthough you might want better granularity, so Nanoseconds might be a better authoritative representation. Anyhow, adding classes of lower granularity won't be a problem -- e.g., hours or days.

    edit: You might want to look at boost::date_time for inspiration, it is fascinating reading.