Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable pattern redundancy in Ruby

The Observable module uses change method as a way of toggling when the observers should get updates of any change in state in the Subject. However, it seems redundant to me, as notify_observers(self) it is going to be called intentionally. Is there a situation where having change makes a difference?

like image 243
borjagvo Avatar asked May 06 '26 10:05

borjagvo


1 Answers

It allows for a split in timing, and for multiple changes without side effects.

  • The state of an object may or may not change during a sub-process of an application. If it changes, then .change can be invoked without any side effects. It is also possible to call it multiple times.

  • Later, notifications can be sent. As long as they are sent before any dependent actions are taken, then anything that depends on updates due to the original change should be able to make its update correctly

You might do this for example if processing following a change had a high cost (I/O, CPU time, network bandwidth), but only needed to be done before a second section of code, not simply every time a change occurred.

You might also do this if updates are not strictly necessary in all code paths. I.e. sometimes you care about updating due to a change, but other times it is not necessary, and any change can be ignored.

An example might be if you need to re-generate an XML document every time a content object used by the XML creation code has a property change. You would place calls to .change in the important property setters of the content object, hiding them from the external caller. You don't want to generate a new XML document each time you call content.property= (it could be very slow), instead you wait until you are finished making updates and place a single call to content.notify_observers after all possible changes.

like image 98
Neil Slater Avatar answered May 07 '26 23:05

Neil Slater



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!