views:

43

answers:

3

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.

+2  A: 

Sure there is: create a class which will represent duration and throw in a couple of factory methods to create an instance of Duration class from seconds and milliseconds:

class Duration
{
    public static Duration FromSeconds(int seconds)
    {
        // ...
    }

    public static Duration FromMilliseconds(int milliseconds)
    {
        // ...
    }        
}

This class should provide single (preferably read-only) property -- for instance, Milliseconds, which will return a number of milliseconds encapsulated in a particular instance.

Additionally, you can have Seconds property.

I'd avoid any implicit conversion operators here (if your compiler allows for them) since they will only complicate matters here.

You can take a look at TimeSpan for inspiration (or use it altogether, if you're on .NET).

Anton Gogolev
+1 This is called the **Value Object** pattern.
Mark Seemann
I googled it, but I can't find a definition of Value Object Pattern that matches yours. Do you have a source?
KaptajnKold
+2  A: 

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.

Hassan Syed
A: 

In Apple's Cocoa, the type for durations is NSTimeInterval and is defined as a double:

typedef double NSTimeInterval;

It is expressed in seconds and has a sub milli-second precision over 10000 years.

mouviciel