[Solved] how to refactor multiple For Loops [closed]


(This is for C#, back when there was a C# tag. Not sure how this converts to java)

You can write a method that takes an integer that represents how many times you want to execute some method, and that takes an Action or delegate for the method to execute:

private static void ExecuteNTimes(int n, Action method)
{
    for (int i = 0; i < n; i++)
    {
        method();
    }
}

Then, if you have some simple methods with the same signature as in your example:

private static void Method_1()
{
    Console.WriteLine("Executed Method_1");
}

private static void Method_2()
{
    Console.WriteLine("Executed Method_2");
}

private static void Method_3()
{
    Console.WriteLine("Executed Method_3");
}

private static void Method_4()
{
    Console.WriteLine("Executed Method_4");
}

You can execute them in your main code like:

private static void Main()
{
    var numTimesToExecute = 3;

    ExecuteNTimes(numTimesToExecute, Method_1);
    ExecuteNTimes(numTimesToExecute, Method_2);
    ExecuteNTimes(numTimesToExecute, Method_3);
    ExecuteNTimes(numTimesToExecute, Method_4);

    Console.Write("\nPress any key to exit...");
    Console.ReadKey();
}

Output

enter image description here

1

solved how to refactor multiple For Loops [closed]