Refactoring Raw For-Loop C++ to Modern Standards
Step 1: The Legacy Code
Here's typical legacy C++ code that checks if any number in a collection is positive. It works, but it's verbose and error-prone. The intent is buried in implementation details.
Step 2: Use Range-Based For Loop
📚 Guideline:
First improvement: eliminate the manual index management. Range-based for loops are less error-prone and more readable. We avoid off-by-one errors and make the iteration intent clearer.
Step 3: Use Standard Algorithm
Replace the manual loop with `std::any_of` - a standard algorithm that expresses our intent directly. This is self-documenting code: we're checking if any element satisfies a condition.
Step 4: Use Ranges (C++20)
📚 Guideline:
With C++20 ranges, we eliminate iterator verbosity. The code becomes even more concise and expressive. Ranges compose better and are less error-prone than iterator pairs.
Step 5: Extract Named Predicate
Give the lambda a meaningful name. This improves readability and enables reuse. The predicate can now be tested independently and used in multiple places.
Step 6: Clean Up with Using Declaration
📚 Guideline:
Remove namespace clutter from the main logic. Using declarations make the code more readable while keeping it clear where the function comes from at the top of your scope.
Loading...