trustmaster / goflow

Flow-based and dataflow programming library for Go (golang)
MIT License
1.6k stars 125 forks source link

Encapsulate the finish semaphore in example code #13

Closed kortschak closed 10 years ago

kortschak commented 10 years ago

Just a small change to the example code to encapsulate the finish chan

kortschak commented 10 years ago

chan struct{}

You're not interested in the value of the send, just that the block is removed; you're always sending true. In this case it doesn't make much difference, but bool has a non-zero size, while struct{} has a zero size. More significantly it signals to the reader that it's just being used a place holder.

Wait()

You want to only expose a send-only chan so the client cannot perform a close which would likely result in a close on close panic. We can achieve this in a couple of ways. As I've done, which is keep an private bidirectional chan and return a send-only chan from a method, or alternatively keep two chans, one bidirectional private and one send-only public that are backed by the same make:

type component struct{
        done chan struct{}
        Done <-chan struct{}
}

done := make(chan struct{})
c.done = done
c.Done = done

This way when the done chan is closed, the closed state is reflected in the published send-only Done chan (note that we can't keep just one, send-only, since we can't close that). I like this less because there is a distance between the connection between the chans and the effect (to understand what's going on you need to see that they are backed by the same chan), though it is valuable in other places (I think tomb uses this approach).

trustmaster commented 10 years ago

Thanks for explanation, now it makes sense.