3 ms·
What do you use generators for?
by neals 2y ago
What do you use generators for?
- steve_adams_86 2y agoThat’s a great question. They work really well for reusing encapsulated logic in predictable ways. If you yield generators from within generators, it’s very easy to anticipate the flow of how they will execute, even if it’s conditional. It’s also very easy to do it asynchronously. Apart from that, you can write logic which is agnostic of the flow it’s in, which makes it so you can yield it from any flow as long as the logic suits it. This makes it so something like a request and retry flow can use the same generators as an exponential back off version of the same logic, or you could drop the retry generator into database access logic, file upload or retrieval, and so on. If the retry logic is generic enough, it’ll be totally reusable. Another use case is creating enormous or potentially infinite data structures which you can easily read and even manipulate. You can generate a deck of cards with just the suits and ranks, for example. If you add orders of magnitude to that scale factor, it still works just as well. You can also easily wrap generators in a class or otherwise to make the app-facing logic nicer to look at. For personal projects I don’t bother, but I’ve done this at various jobs where I knew a dead-simple wrapper would dramatically clean up and simplify working with the generator while providing the same capability. It really depends on how much or how little can be abstracted and if it’s worthwhile. I know you could say “but I can do this with promises” or similar, and in some cases you can (definitely not massive or infinite data traversal), but the control of the flow with a generator is remarkably powerful. Sometimes that’s very useful.