Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observer pattern forces imperative style

I was looking at the Reactive Programming course from Coursera, which uses Scala to implement an Observer pattern. There, Martin Odersky says that the Observer pattern forces Imperative Programming, which we can see because the subscriber's handlers have Unit type.

He is saying that here: https://class.coursera.org/reactive-002/lecture/107 At 9:40

I don't really understand:

1.Why do the handlers need to have Unit type?

2.How is the Observer pattern forcing Imperative Programming?

like image 300
octavian Avatar asked Jan 07 '23 00:01

octavian


2 Answers

I have not reviewed the video posted, so I am basing my answers on the OP's original question.

Handlers are, by the pattern's definition, callbacks; as such, they have a Unit return type because they describe some behaviour that will be executed in response to the notification. This is the very definition of side-effect.
Hence the statement that the Observer Pattern is an instrinsically imperative pattern: the caller of a function (e.g. notifyObservers(observer) ) does not care on the results of the function itself, but it relies on the side-effects it will have. This is imperative programming.

As a side-note, the fact that Unit is the result type is not strictly necessary but, as previously mentioned, communicates that there is no interest in anything but the side-effects. One could, potentially, model the method generically and return some more meaningful type, but because of the way the Observer Pattern is used in practice, this will probably be ignored anyways...

like image 86
mdm Avatar answered Jan 18 '23 05:01

mdm


Because if they do have the return type other than Unit, the order in which observable calls the handlers becomes significant. Not saying that observable now should be aware of the return types and should be able to handle them, which is not the part of observer pattern.

In general observer pattern means that both observer and observable should have a state, because observer is designed to react to events in observable, and this pattern describes the reaction between the states of those objects.

If you go to wiki and read the observer pattern definition, you will find in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes,, which has the word state in it, which already means that we do not have FP anymore and it cannot be pure

like image 22
Archeg Avatar answered Jan 18 '23 06:01

Archeg