From: Avdi Grimm Date: 2008-05-24T04:22:06+09:00 Subject: Re: Ruby observer module On Fri, May 23, 2008 at 2:49 PM, S2 wrote: > I also have another question: why does the subject (the notifying class) > need to call "changed"? Wouldn't it be sufficient to call notify_observers? > I mean, if I call notify_observers in the Subject class, doesn't that imply > has something has changed? Consider the case: def do_stuff step_that_might_change_self() another_step_that_might_change_self() yet_another_step_that_might_change_self() end Any of the methods called by do_stuff MIGHT change the data, but then again they might not. do_stuff should appear as an atomic operation from outside the object, so we don't want to call notify_observers in all three methods. What we really want to do is do all of the steps and then, when they are finished, notify our observers - but only if we've actually been changed. So we write it like this: def do_stuff step_that_might_change_self() another_step_that_might_change_self() yet_another_step_that_might_change_self() notify_observers end And then it is each step's responsibility to call #changed if and only if they actually made a change. If a change was made by one or more steps, our observers are notified ONCE at the end. -- Avdi Home: http://avdi.org Developer Blog: http://avdi.org/devblog/ Twitter: http://twitter.com/avdi Journal: http://avdi.livejournal.com