# Can I improve this code using delegates?

Posted on

Problem

I guess I might use delegates. But I’m not certain if I can apply for it.

Sorry if the code is a mess. I’m a beginner and am still learning. For that reason, I need a little of help to improve this code. It’s not finished.

I’m creating a Math quiz system. And there are many questions as you will be able to see in it, they’re so different and I have a difficult moment to create the classes.

``````    private int[] Generate_Fraction(int li1, int ls1, int li2, int ls2)
{
int numerator = randomizer.Next(li1, ls1);
int denominator = randomizer.Next(li2, ls2);

int[] fraction = new int[2];
fraction[0] = numerator;
fraction[1] = denominator;

return fraction;
}

// Decimals
private double[] GeneratePattern5(double[][] limits)
{
double[] decimals = new double[limits.Length];
for (int i = 0; i < limits.Length; i++)
{
bool flag;
double decTemp;

do
{
flag = false;
decTemp = GetDoubleBetween(limits[i][0], limits[i][1], (int)limits[i][2]);

if (Exists(decimals, decTemp, i))
{
flag = true;
}

} while (flag);

decimals[i] = decTemp;
}

return decimals;

}

// Fractions like: 6/60
private int[][] GeneratePattern7(int[][] arrayLimits)
{
int[][] fractions = new int[arrayLimits.Length][];
for (int i = 0; i < arrayLimits.Length; i++)
{
bool flag;
int[] fracTemp = new int[2];
do
{
flag = false;
fracTemp = Generate_Fraction(arrayLimits[i][0], arrayLimits[i][1], arrayLimits[i][2], arrayLimits[i][3]);
fracTemp[1] *= fracTemp[0];

if (Exists(fractions, fracTemp, i))
{
flag = true;
}
} while (flag);

fractions[i] = fracTemp;
}

return fractions;
}
``````

Solution

Unless I’m missing something, you can move the Exists inside the condition and remove the flag variable. This will change the loop to…

``````        double decTemp;

do
{
decTemp = GetDoubleBetween(limits[i][0], limits[i][1], (int)limits[i][2]);
} while (Exists(decimals, decTemp, i));
``````

I believe that this is more semantically in line with what you are trying to accomplish. You could do the same thing inside the GeneratePattern7 method as well. Doing so will reduce a lot of clutter.

You can remove duplication from this code. There are a couple of ways to do this but as a result you’ll get really complicated code. I think you should leave it as it is now. There are situations when it’s better to have some duplication than to have complicated code.