The other day, and interesting discussion came up with co-worker Jamie. The question is within a given system, is it better to push or pull data. Put another way, should I poll and go get the data I need – or should I ask objects to report back to me when they have new data for me.
Depending on the situation, they both have merit – but usually, “push” tends to be the answer. But, I wanted to explore that further. So, I spent a little time proving out an example. First, I created an interface for monitoring “something”:
So next, I created a polling version of a class that monitors the weather.
The thinking here is that we leave the “responsibility” of retrieving the data to the consumer. In other words, this just provides a mechanism which allows consumer to manually poll.
I then created an event-driven class that gets weather conditions. This is markedly more complex, as it has more “responsibility”:
At this point, it seemed that the polling approach might be the way to go – since it is less code. However, when I started to figure out what the consumer would look like, I realized I would need a LOT more code on any consumer that used the polling technique.
Put another way, there is a fixed amount of work/logic to be done – the question is, where do you want to do it? Whose “responsibility” is it to poll for new data and report to subscribers that there is an update?
I argue that it is the provider of the data.
When we use the polling approach, every consumer of that class must write their own logic for starting, stopping (pausing?) monitoring. Whereas the push approach leaves all of that responsibility to the provider class. All we need to do is call .StartMonitoring(), .StopMonitoring() – and wait for the event to fire.
Although every situation is different, the conclusion I come to is that from Single Responsibility Principle sort of way, and from a loose-coupling sort of way – in a case like this, you should probably have the providers of data “push” data at their discretion rather than the consumers doing all that heavy-lifting.