Refactoring Loops
Part of the Logic & Flow section of Coddy's C# journey — lesson 16 of 66.
Refactoring loops can improve code readability and maintainability.
Replace traditional loop with foreach for simplicity:
string[] fruits = { "apple", "banana", "cherry" };
// Before refactoring
for (int i = 0; i < fruits.Length; i++)
{
Console.WriteLine(fruits[i]);
}
// After refactoring
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}Extract complex loop logic into methods:
int[] numbers = { 1, 2, 3, 4, 5, 6 };
// Before refactoring
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] % 2 == 0)
{
Console.WriteLine($"{numbers[i]} is even");
}
}
// After refactoring with helper method
for (int i = 0; i < numbers.Length; i++)
{
if (IsEven(numbers[i]))
{
Console.WriteLine($"{numbers[i]} is even");
}
}
// Helper method
bool IsEven(int number)
{
return number % 2 == 0;
}Break large loops into smaller, more focused loops:
int[] data = { 1, 2, 3, 4, 5 };
// Before: One large loop doing multiple things
for (int i = 0; i < data.Length; i++)
{
// Process data
data[i] = data[i] * 2;
// Print results
Console.WriteLine(data[i]);
}
// After: Separate loops with clear purposes
// Process data
for (int i = 0; i < data.Length; i++)
{
data[i] = data[i] * 2;
}
// Print results
for (int i = 0; i < data.Length; i++)
{
Console.WriteLine(data[i]);
}Challenge
MediumCreate a method called refactorArrayFilter that:
- Takes an array of integers as a parameter
- Implements two versions of code that count numbers divisible by 3:
- Original: Use a traditional for loop with an if statement
- Refactored: Use a foreach loop with the logic extracted to a helper method
- Returns the count from the refactored version as an integer
For example, given the array [3, 4, 6, 7, 9], the method should return 3 because there are three numbers (3, 6, and 9) that are divisible by 3.
Note: You don't need to print anything - just return the count as an integer.
Cheat sheet
Use foreach instead of traditional for loops for simpler array iteration:
// Traditional for loop
for (int i = 0; i < fruits.Length; i++)
{
Console.WriteLine(fruits[i]);
}
// Refactored with foreach
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}Extract complex loop logic into helper methods:
// Before refactoring
if (numbers[i] % 2 == 0)
{
Console.WriteLine($"{numbers[i]} is even");
}
// After refactoring with helper method
if (IsEven(numbers[i]))
{
Console.WriteLine($"{numbers[i]} is even");
}
// Helper method
bool IsEven(int number)
{
return number % 2 == 0;
}Break large loops into smaller, focused loops with single responsibilities:
// Before: One loop doing multiple things
for (int i = 0; i < data.Length; i++)
{
data[i] = data[i] * 2; // Process
Console.WriteLine(data[i]); // Print
}
// After: Separate loops with clear purposes
for (int i = 0; i < data.Length; i++)
{
data[i] = data[i] * 2; // Process only
}
for (int i = 0; i < data.Length; i++)
{
Console.WriteLine(data[i]); // Print only
}Try it yourself
public class RefactorArrayFilter
{
// Implement the refactorArrayFilter method
public static int refactorArrayFilter(int[] numbers)
{
// Write your code here
}
// Implement any helper methods you need
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety