begin quoting Tracy R Reed as of Mon, Jan 07, 2008 at 01:59:01AM -0800: > I hate to drag this incredibly interesting yet simultaneously tedious > conversation into the realm of the practical but... > > Gabriel Sechan wrote: > >Seriously, though. A variable *always* has a type, wether the language > >does or not. The type of a variable is the kind of data it holds. This > >is separate from its languae type. For example, lets say we have to store > >today's temperature. Its type is temperature in degree's celsius. Its > >language type may be scalar in perl, int in C++, etc. But its true type > >is still temperature in degrees celsius. Having a language that supports > >typedefs and declarations merely documents that for you, rather than > >forcing you to read the code to figure it out. > > Can you somehow encapsulate units in a type so that when we program a > completely hypothetical Mars lander it doesn't allow us to accidentally > mix meters and feet without doing a type conversion? I don't mean just > having an integer typecast to "altitude" but somehow call it "altitude > in meters" without being so verbose? And for bonus points it would be > nice if it could prohibit the involvement of any other units of distance > in the calculation so we don't accidentally mix our altitude in meters > with our rate of descent in feet per second during our retro-rocket > timing calculations.
That's what objects do. Or are supposed to. I generally see three approaches (besides trying to normalize all data): (1) Define a new subclass for every type. You don't have "int altitude", you have "Altitude altitude", and you then have concrete subclasses of Altitude such as "AltitudeMeters", "AltitudeFeet", "AltitudeHg", etc. (2) Define a set of constants (or an enumeration) for each type, and pass it in as an extra parameter to the general-type class. Thus, every method gets more parameters, e.g., altitude.add( 3500, Altitude.METERS). (3) Define methods to handle each type; e.g., altitude.subtractMeters(300). Operator overloading supposedly helps with this, but then the operators get overloaded to do all manner of strange things, such as bit-shifting a stream by a string, or + being overridden do to division. -- So many strong promises are broken When performance is the only token Stewart Stremler -- [email protected] http://www.kernel-panic.org/cgi-bin/mailman/listinfo/kplug-lpsg
