Another neat feature of generators is that they let you factor out things that are logically separate but are all munged together in your existing code.
For example, you might have a complicated while loop that gets stuff from a queue and breaks when the queue is exhausted. The queueing algorithms, locking, and so forth might be partly wormed in with the rest of your code, which actually processes whatever you've gotten from the queue. You want to refactor this into two parts: looping code and processing code. (Maybe because you want to reuse the basic loop structure to process different stuff.)
Where I work (C++), they'd just copy a bunch of code. Without generators or blocks, refactoring this code is a huge pain. You'd either have to rewrite the looping code as a pullable iterator; or else rewrite the processing code as a pushable visitor. Generators let you separate them without rewriting either one.
No comments:
Post a Comment