Paul Laguna
Paul Laguna

Reputation: 75

How do I shorten this C# code when having many if conditions in a single statement

I'm using this function to check if certain privacy policies are displayed in the UI. If x policy is displayed, then click the 'i agree' button to go to the next page to check if y policy is displayed. if not displayed, then flag an error. This process will repeat until all the policies are checked.

We have 4 privacy policies, which we can switch on or off. So sometimes 2 or 3 policies would only appear instead of 4. If 2 or 3 policies only show that's fine, and shouldn't break the test. Hence all the if s. Is there anything I can use instead of so many if s? I feel like I have way many if s under a single method.

public static void CheckPolicy(bool privacyPolicy1Expected = true, bool privacyPolicy2Expected = true, bool privacyPolicy3Expected = true, bool privacyPolicy4Expected = true)
    {
        if (privacyPolicy1Expected) { PP1AgreementValidation(); }
        if (!privacyPolicy1Expected) { App.AssertElementNotPresent(_privacyPolicy1Header); }
        if (privacyPolicy2Expected) { PP2AgreementValidation(); }
        if (!privacyPolicy2Expected) { App.AssertElementNotPresent(_privacyPolicy2Header); }
        if (privacyPolicy3Expected) { PP3AgreementValidation(); }
        if (!privacyPolicy3Expected) { App.AssertElementNotPresent(_privacyPolicy3Header); }
        if (privacyPolicy4Expected) { PP4AgreementValidation(); }
        if (!privacyPolicy4Expected) { App.AssertElementNotPresent(_privacyPolicy4Header); }    
    }

I get no errors. The code works fine. I just need to shorten this up a bit or use a different function to shorten the code.

Upvotes: 0

Views: 330

Answers (2)

Diven Desu
Diven Desu

Reputation: 41

If your looking to really shorten it up I would suggest a ternary operator

privacyPolicy1Expected ? PP1AgreementValidation() : App.AssertElementNotPresent(_privacyPolicy1Header);

It works like a compact If/Else statement. It test the condition before the "?" if true it execute the code before the ":" if it test false it will execute the code after the ":".

Upvotes: 0

Owen Pauling
Owen Pauling

Reputation: 11871

You are checking if a condition is true, then again checking it is not true. You can re-write that as an if else.

 if (privacyPolicy1Expected) { PP1AgreementValidation(); }
 if (!privacyPolicy1Expected) { App.AssertElementNotPresent(_privacyPolicy1Header); }

becomes:

if (privacyPolicy1Expected) 
{ 
    PP1AgreementValidation(); 
}
else 
{ 
    App.AssertElementNotPresent(_privacyPolicy1Header); 
}

Upvotes: 1

Related Questions