What are some best practices?
The following are a few best practices to consider when working with generic code:
- Use functions over methods: A method is a function associated with a type and is called with a receiver; therefore, a function in the context of generics is more flexible, as it is not tied to a specific type. This allows for easier reuse and the ability to compose functions with different types.
- Ease of transformation: It is easier to turn methods into functions than it is to add a function to a type. Functions can be defined independently of specific types. In the context of generics, you can use generic functions with any type that satisfies the required constraints. If it later makes sense to convert to a method, then you can do so without modifying the original function more easily.
- Prefer functions over constraints that require methods: Instead of defining constraints that specifically require a method on a type, prefer using functions that work with...