From: Devin Mullins Date: 2005-09-28T12:22:03+09:00 Subject: Re: Class and Iterator Design Question Hi, Jim. Don't worry. All design questions are silly, but I don't mind pontificating. :) I think I'd return an Array or Set or something. 1. It's just easier to write the Pod class that way (as you showed). 2. It's just easier to use the Pod class that way. Array & Set map more closely to what you're exposing (a finite list with random access) and provide methods that might be helpful to the user, such as #+ and #empty?, that Enumerable doesn't provide. However, as a rule of thumb, I'm lazy, so I may be biased. If you don't like the idea of exposing your internal Array or Set, you're welcome to wrap it in some sort of Decorator class (say, to make it immutable) before returning it -- that's a common Java idiom (*ahem* I mean "pattern"; I must not have been served the right Kool-Aid). The awfully cool APIs will actually return a "live" Array, where modifying the array or its contents through typical-looking Array methods actually triggers the backend logic to do its thang. Devin Jim Freeze wrote: >This may be a silly design question, but I always balk at >the right answer when I am confronted with it. > >I have a class that manages a list and users need to iterate over that list. >The way I see it, I have to basic alternatives: > > # Give user access to the array and let them iterate over Array > class Pea > attr_reader :pods > end > Pea.new.pods.each { |pod| ..do stuff.. } > >or > > # Provide a custom iterator > class Pea > def each_pod > @pods.each { |pod| yield pod } > end > end > Pea.new.each_pod { |pod| ..do stuff.. } >end > >In other words, for classes that manage a list of items, >do people prefer to see a custom iterator, such as #each_, >or do they prefer getting back an array and iterating >over it themselves, such as #.each? > > Pea.new.each_pod { |pod| ..do stuff.. } > Pea.new.pods.each { |pod| ..do stuff.. } > >Cheers >-- >Jim Freeze > > > >