Dan
Dan

Reputation: 57921

Need a library or design pattern for dealing with dependency hell in asynchronous code

I will describe a simplified example of such "dependency hell".

Imagine a video player with "play/pause" and "mute/unmute" buttons. Pausing the video should pause sound but not mute it, so that unpausing the video should unpause audio.

Then imagine we are downloading audio and video in separate files, so we have four success/error callbacks. Imagine video can play without audio but not conversely. Now imagine how many changes should be made to the code if the requirements update so that video and audio should wait for each other.

Currently I'm dealing with this using callbacks and boolean variables. I have a feeling this is stone age, because something like this:

if (videoShouldPlay && audioShouldPlay && isAudioPlaying && isVideoDownloaded && isAudioDownloaded) {

or 4 similar callbacks:

audio.onload = function () {
    if (isVideoDownloaded)
       .....
    } else { ...
}

is neither readable nor maintainable. The number of dependencies grows exponentially with the number of components, but I should not track every dependency when I can define some general rules .

I'm sure computer science has solved this problem already.

Upvotes: 0

Views: 87

Answers (1)

Ali
Ali

Reputation: 58501

It looks like to me you need a state machine. Let's take for example the states "playing" and "paused". The rule for the transition "playing" ➜ "paused" would be what you write: "Pausing the video should pause sound but not mute it", etc. It's hard to tell more about it without seeing the actual problem you have at hand.

I would recommend Chapter 29 State from Agile Software Development, Principles, Patterns, and Practices and Replace State-Altering Conditionals with State from Refactoring to Patterns. I personally find the famous Design Patterns: Elements of Reusable Object-Oriented Software book somewhat difficult to read, nevertheless it is the State pattern in it.

Upvotes: 2

Related Questions