Buffering is one of the unique features of conduits. With buffering, conduits no longer need to control the flow of your application. In some cases, this can lead to simpler code.
Buffering was actually one of the main motivations in the creation of the
conduit package. To see its importance, we need to consider the approach we’ve
seen so far, which we’ll call inversion of control, or IoC.
Inversion of control can mean different things in different circles. If you object to its usage here, go ahead replace it with some other phrase like “warm, fuzzy thing.” I won’t be offended.
Suppose you want to count how many newline characters there are in a file. In the standard imperative approach, you would do something like:
Open the file.
Pull some data into a buffer.
Loop over the values in the buffer, incrementing a counter on each newline character.
Return to 2.
Close the file.
Notice that your code is explicitly calling out to other code, and that code is returning control back to your code. You have retained full control of the flow of execution of your program. The conduit approach we’ve seen so far does not work this way. Instead, you would:
Write a sink that counts newlines and adds the result to an accumulator.
Connect the sink to a source.
There’s no doubt in my mind that this is an easier approach. You don’t have to worry about opening and closing files or pulling data from the file. Instead, the data you need to process is simply presented to you. This ...