From: Hugh Sasse Date: 2005-09-28T01:10:23+09:00 Subject: Re: Class and Iterator Design Question On Wed, 28 Sep 2005, 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.. } > Which exposes implementation somewhat, but.... > or > > # Provide a custom iterator > class Pea > def each_pod > @pods.each { |pod| yield pod } > end # Maybe:- alias :each :each_pod > 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.. } I'd expect Pea.new.each{ |pod| ... ] because you might change your list to a Set or tree or soemthing later. Unless you normally iterate over something else... (But having said that, I'd expect a Pod to contain Peas :-)!) > > Cheers > -- > Jim Freeze > > Hugh