2 ms·
Yes, officially, channels should be rarely seen in library APIs. This is because most of the time the library is doing something that should be simply done sync
by jerf 8y ago
Yes, officially, channels should be rarely seen in library APIs. This is because most of the time the library is doing something that should be simply done synchronously. If a consumer of your library wants to do something with that synchronous operation, it is up to them to use the concurrency tools to do so. You can't provide a library that is as flexible as what the language already offers, because you can't help but hard-code some aspect of what is going to be done.
But there are rare cases where you may want to offer them. I find a pattern I often have is to officially provide a method or set of methods that do whatever the thing is, but if you have a sophisticated case where you may need the thing the library is doing to participate in a select, you can offer a channel. There's often additional responsibilities for the caller that come with it when I do that. But it's more efficient that asking them to spawn a brand new goroutine just to call my code that is just going to drain a channel for them. Some particularly advanced fixtures may even have their own internal plumbing bits, but you normally shouldn't care about those.
Channels are fairly composible, it's just that it shouldn't be libraries doing the composing. To use a rough physical equivalent, your sink, dishwasher, toilet, and shower don't come with their own pipes to hook into the system, because whoever made those things have no idea what your local concerns will be. Fixtures are the library functionality, and the channels are the local plumbing. It's not a perfect metaphor, since physical objects intrinsically fix more aspects than code does, so don't pick at it too hard, it's just something to get an idea across.
(They'll get more composable with the new generics stuff, when it comes out. Although possibly dangerously so; generic channel libraries are going to make it easy to compose yourself up some local plumbing that involves way too many hidden goroutines and channels and will make it easy to trash performance.)