67. Don’t write unintentionally nongeneric code

Summary

Commit to abstractions, not to details: Use the most generic and abstract means to implement a piece of functionality.

Discussion

When writing code, use the most abstract means available that get the job done. Think in terms of what operations put the least “capabilities strain” on the interfaces they operate on. This habit makes your code more generic, and therefore more reusable and more resilient to changes in its surroundings.

On the contrary, code that gratuitously commits to details is rigid and fragile:

Use != instead of < to compare iterators: Using != is more general and so applies to a larger class of objects; using < asks for ordering, and only random-access iterators can ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.