From: Paul Sanchez Date: 2004-06-08T13:13:40+09:00 Subject: Re: Interfaces and semantics (or, how to hashpipe a duck) Hal Fulton wrote: > Semantics, James Thurber notwithstanding, is not a town in Ohio. > > I think when Rich says "semantics" he means something that can't > really be checked by a machine -- the "purpose or function," as it > were. > > I do sometimes wish there were a way to detect semantics -- but the > best we could do is simply remove the problem a step further. > > Warning: I'm tired, so I'm not expressing myself as well as I might > at a different time of day. > > > For example, imagine that we are concerned with a conceptual "append" > operation. We want to know whether an object is capable of being > appended onto. > > Well, a string is "appendable." So is an array. So is a file. > > str << x > arr << x > file << x > > Aha! Why not just check for << existing? > > Oops. There's a Fixnum#<< which does a left shift! > > In short, the first three have very similar semantics, but the > last is very different. > > I have at times (almost) wished for a thing rather like Java interfaces: > > obj.implements?(Append) # where Append is some sort of interface > # whose conceptual semantics are agreed on > > Sure, modules in Ruby can serve that purpose. But it's rather > inefficient to have 10-15 modules included in a class (especially when > most methods will be redefined anyway). > > But even if we had #implements? -- would it really solve anything? Not > necessarily. We would still have to deal with programmers who were > careless, ignorant, or misinterpreted the docs. > > Just the random firings of my neurons. Ignore at your leisure. > > > Hal Fulton This is what I was trying to say earlier today. The syntax "<<" in your example is overloaded with regard to semantics (meaning) - it means substantively different things for arrays vs hashes. This is true right out of the box in Ruby for "<<" and "[]". The only way to avoid the problem, so far as I can see, is to use a syntax which is unique to the semantics you wish to represent - in Ruby that means picking a new method name+#args, because without type information there's nothing else to clue in on. The solution for Sean is to not use "[]". Either use an existing method alias which is not semantically overloaded when writing new hash-like classes, or create a new alias (for instance by writing a wrapper method) which is not semantically overloaded for hashes and use that method name for your hash-like classes. --paul