Search code examples
ooplanguage-agnosticcomputer-scienceliskov-substitution-principle

Type safety with object-oriented methods


I'm trying to think of how to solve this problem correctly using object-oriented methods. The language isn't important—I would actually like to write code, but it's more the general principles I care about.

I want to implement a field: a collection of 'numbers' on which the operations +, -, *, and / operate. Further, I would like to be able to implement higher operations like ^ and cycle-finding which (1) do not need to be defined for a given field but which (2) can be overridden if desired, say for efficiency reasons.

Here's the catch. It's not good enough to declare

FieldElement power (FieldElement base, FieldElement exponent)

because I want type safety: it should not be possible to add, say, a member of a finite field to an integer.

Perhaps what I'm really looking for is a meta-object, or super-interface, or something that ties together different classes (one for integers, one for 7-adics, one for the finite field F_4, etc.). Or maybe there's something better.

N.B. Code is welcome (even encouraged) in answers, if it would be enlightening, but declarations are probably enough: presumably everyone here could write out the obvious methods for at least a few fields.


I'll mention other conditions which matter to me but are (apparently) unrelated to the main OO issue: I don't want field elements to carry their type information around, and further I want them to be lightweight (since I may need to deal with large arrays of field elements). These desiderata may not be achievable—though frankly I'm more likely to abandon OO here than efficiency. But an answer would be appreciated regardless, since I'm interested in learning about these issues even apart from the particular problem at hand.


Solution

  • This is called the binary method problem. Quick googling will reveal some (lots of) information. In particular, the article "On binary methods" by Luca Cardelli et al gives the subject a thorough treatment.

    You may want to learn some Haskell to see how a practical programming language deals with this problem.

    EDIT Loluca → Luca. Damn the tiny phone screen and its tinier keyboard ;)