Dr. David J. Pearce

The Case Against Structural Subtyping ... ?


My previous post on structural subtyping generated quite a few comments over on reddit.  There were a lot of mixed opinions as to the pros and cons of having a structural type system instead of a nominal type system. To help me digest and ponder it all, I thought I’d discuss the main themes here in more detail.

Issues

I’ll start by looking at the various issues people highlighted with structural subtyping, and provide a few comments of my own later.

Comments

In my opinion, many of the issues raised above can be adequately resolved with a little bit of care and thought.  Let’s consider the easy ones first:

Now, the issue of maintaining invariants in a structural subtyping system appears (to me at least) to be the hardest of all.  Here’s my take on it:

Neither of these two solutions are really satisfying for me!  Now, all of this discussion (from my perspective at least) is in the context of the Whiley language.  The aim of this language is to make invariants first-class entities which are checked at compile-time by the compiler.  In such a setting, the invariants can be explicitly written as part of the structural type, thereby eliminating this problem altogether!  For example, with the Date class from before, we might have:

define Date as { int day,int month,int year } where
 0<=day && day<=31 && 0<=month && month<=12 && ...

The beauty of this, is that we can now only interchange Dates with structures that have suitable invariants as well. However, the invariants need not match exactly. For example:

// a date with no invariant
define DumbDate as { int day, int month, int year }
// a date in Februrary
define FebDate as Date where $.month == 2

DumbDate f(Date x):
    return x

DumbDate g(FebDate y):
    return f(y)

Here, we see that records can flow into variables requiring structural subtypes with invariants which are no stricter. This gives an interesting advantage over the nominal type solution to this problem…

Righto, that’s enough thinking for now!!