www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Another typedef usage example

reply bearophile <bearophileHUGS lycos.com> writes:
Another usage example of the strong typedef of D1. This his D2 code, it shows
how it can catch bugs in combineRectangles():


import std.algorithm: max, min;

typedef int Length;
typedef Length HorizPosition;
typedef Length VertPosition;

struct Point {
    HorizPosition x;
    VertPosition y;
}

struct Rectangle {
    Point upperLeft, lowerRight;
}

// Length is defined as a generic form of HorizPosition and VertPosition
// because of the typedefs. There is no problem when combining a
// generic type with a type lower on the hierarchy.

Length perimeter(const ref Rectangle r) {
    // Length len = 2 * (r.upperLeft.y - r.lowerRight.y); // problem
    Length len = 0;
    len += 2 * (r.upperLeft.y - r.lowerRight.y); // combining VertPosition with
Length
    len += 2 * (r.lowerRight.x - r.upperLeft.x); // combining HorizPosition
with Length
    return len;
}

/// To form one large rectangle that will just cover the rectangles r1 and r2.
Rectangle combineRectangles(const ref Rectangle r1, const ref Rectangle r2) {
    return Rectangle(Point(min(r1.upperLeft.x, r2.upperLeft.x),
                           max(r1.upperLeft.y, r2.upperLeft.y)),

                     // Here HorizPosition and VertPosition need to be
                     // treated as two separate and distinct types
                     Point(max(r1.lowerRight.y, r2.lowerRight.x), // Err
                           min(r1.lowerRight.x, r2.lowerRight.x))); // Err
}

void main() {}


Bye,
bearophile
May 05 2010
parent Shin Fujishiro <rsinfu gmail.com> writes:
Yet another example:
--------------------
typedef string URIEscapedString;
URIEscapedString escapeURI(string s);
void[] requestWebResource(URIEscapedString safeuri);

void main() {

        // Error: cannot implicitly convert ...
}
--------------------
In this code, you cannot pass a "raw string" to requestWebResource().
Any raw string must be URI-escaped with escapeURI() before used as a
valid URI, or it won't compile.

This would be applicable to SQL sanitization, input validation, etc.

--
I read it somewhere that some programmers use Hungarian notation to do
the same thing.  But Hungarian prefixes are not checked by compier.
May 08 2010