Smithy
Smithy

Reputation: 176

Refactoring If Statements

I have to create a grading system for my C# programming assessment and I'm currently trying to refactor redundant code.

foreach (Student item in mark)
{
    if (ComboBoxGradeMethod.SelectedIndex == 0)
    {
        item.Grade = vetMethod.VETGrade(item.Mark);
    }
    else if (ComboBoxGradeMethod.SelectedIndex == 1)
    {
        item.Grade = newVETMethod.VETGrade(item.Mark);
    }
    else if (ComboBoxGradeMethod.SelectedIndex == 2)
    {
        item.Grade = gradeMethod.CollegeGrade(item.Mark);
    }
    else
    {
        MessageBox.Show("Please select a grading scheme.");
    }
}

Here in this 'for each' loop are 3 if statements. A friend of mine said I can reduce the code by creating a method and passing a function as a parameter.

I'm a beginner programmer and what he said is a bit beyond me at the moment. I was wondering how I would go about doing it? I don't want the entire answer, just how to go about doing it.

Upvotes: 3

Views: 164

Answers (2)

Enigmativity
Enigmativity

Reputation: 117064

Assuming that item.Mark is an int and item.Grade is a string then this is how I would do it:

var gradeFromMarkMethods = new Dictionary<int, Func<int, string>>()
{
    { 0, vetMethod.VETGrade },
    { 1, newVETMethod.VETGrade },
    { 2, gradeMethod.CollegeGrade },
};

Func<int, string> gradeFromMark;
if (gradeFromMarkMethods.TryGetValue(ComboBoxGradeMethod.SelectedIndex, out gradeFromMark))
{
    foreach (Student item in mark)
    {
        item.Grade = gradeFromMark(item.Mark);
    }
}
else
{
    MessageBox.Show("Please select a grading scheme.");
}

Upvotes: 6

Abhinav Galodha
Abhinav Galodha

Reputation: 9878

Few suggestions.

  1. Try using switch case instead of if - else.

  2. Create a function for Assignment of Grade

  3. Try to separate UI controls from the code, you can get the value of the variable from UI controls like ComboBoxGradeMethod and then pass it to the function. The UI may change in future, so it is better to decouple the business logic from UI.

Upvotes: 1

Related Questions