What are blocks?
Gosu blocks are functions without names, which you can define in-line within another function. In other programming languages, blocks are known as anonymous functions. You can then pass that block of code to yet other functions to invoke as appropriate. Blocks are useful for generalizing algorithms and simplifying interfaces to APIs. An API author can design most of an algorithm but let the API consumer contribute short blocks of code to complete the task. The API can use this block of code and call the block either once or possibly many times with different arguments.
For example, you might want to find items within a collection that meet particular criteria, or to sort a collection of objects by certain properties. If you can describe your find or sort criteria using a small amount of Gosu code, Gosu performs the general algorithm such as sorting the collection.
Some other programming languages have similar features to blocks and call them closures or lambda expressions. If you use the Java language, notice that Gosu blocks serve some of the most common uses of single-method anonymous classes in Java. However, Gosu blocks provide a concise and clear syntax that makes this feature more convenient in typical cases.
- Collection manipulation
- Using collection functions such as
mapandeachwith Gosu blocks allows concise, readable code with powerful and useful behaviors for real-world programming. - Callbacks
- For APIs that wish to use callback functions after an action is complete, blocks provide a straightforward mechanism for triggering the callback code.
- Resource control
- Blocks can be useful for encapsulating code related to connection management or transaction management.
Gosu code using blocks appropriately can simplify of your Gosu code. However, blocks can also cause confusion if your code uses them too frequently. If the previous list does not include your intended use, reconsider whether to use blocks. There may be a better and more conventional way to solve the problem. If you write a method that takes more than one argument that is a block, strongly consider redesigning or refactoring the code.
