[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Inheriting Array and slice() behaviour

Devin Mullins

7/6/2005 9:04:00 PM

> > Pedantically, it doesn't quite sound like Expression is-a Array. It
> > doesn't satisfy Array's general contract. (See
> > http://en.wikipedia.org/wiki/Liskov_substitution... .)
> Can you be more specific ? I think it would have if slice returned an
> Array)

Sure. Liskov's Substitution Principle states that if I (say, if I ever get around to finishing Ruby Quiz #35, let alone starting #36 :P) wanted to make use of an array (say, to store a list of captured pieces), you could construct an empty Expression object, hand it to me, and I could mess with it as an Array object, having no idea what "Expression" is.

You're right; your code probably does that now, but it's not meant to. It's not meant to be a general-purpose Array class -- it's simply supposed to be an Expression. I suppose it's in the letter of LSP, but not the "spirit."

Good examples of LSP come from Java. For example, the JDK has a Set interface, which allows you to store a bunch objects with no duplicates. It contains the typical add, remove, contains methods as well as an iterator, which promises to iterate over all of the elements in the Set.

The SortedSet interface derives from Set, and as such, it provides all these methods as well. In addition, it stipulates that the iterator will return the elements in proper order (lexicographical, or numerical, or whatever). This doesn't break anything, because the iterator method of Set didn't care about order. Clients of Set shouldn't care whether or not the elements are being iterated in order or not, so they can use Set or any of its subtypes.

In your case, what if I wanted to generate a list of the first 5000 prime numbers? Should I use your class?

You are right, though, that your Expression class has a lot of Array-like qualities to it. It's something that screams to be iterated. In this case, a better approach might be to implement an Expression#each method, and include Enumerable.

But I'm no expert on this stuff, so don't blame me if I'm way off. :)

Devin
I dunno... I feel like I'm leaving something out...