Hacker News new | past | comments | ask | show | jobs | submit login

> What's the coordinate system? What are the units?

That information can be encoded into the class type, in which case you get compile time checking. I wrote a blog post about this some time ago:

http://www.randomprogramming.com/2014/06/quote-of-the-week-t...

The summary is that we had two different coordinate systems in play and had many bugs caused by passing values in the wrong coordinate system around. By making the different coordinate systems different classes everything became explicit and checked by the compiler. We completely eliminated a whole class of bugs from our program.

The great thing about using an int is that it can be anything (integer). It can be an x coordinate, or the number of eggs or a selection between multiple options.

The bad thing about using an int is that it can be anything, and sooner or later you will pass the number of eggs into a function that really wants an x coordinate.




I prefer having member functions that convert to a different value, and friend functions that create instances from another type:

    Distance d = feet(7);
    d += meters(3);
    std::cout << d.yards();

    Distance d2 = 3; // I won't compile
This assumes that you want to mix units, not defeat it. It all ends up being very efficient; use MKS for the underlying representation. You can multiply, add, and so on, quite efficiently; the only conversions happen on input and output.


> That information can be encoded into the class type

This. I did the very same thing when dealing with some code that was frequently converting between three coordinate systems. Using Haskell code duplication was close to non existent and still type-safe. Not wanting to sound too fan-boyish ... but that was one of the first times that I realized that a good type-system can help you prevent whole classes of bugs.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: