Alexeev Mikhail
Alexeev Mikhail

Reputation: 315

Prevent further execution of calling function in C#

I have a function, which executes on button click and it looks like this

private void Login_Button_Click(object sender, RoutedEventArgs e)
    {
        if (!CheckFields())
            return;

        if (!WritePerforceSettingsXml(rewriteSettingsCheckbox.IsChecked.Value))
            return;

        Dictionary<string, string> installerToUpdateList = new Dictionary<string, string>();
        if (!GetUpdateListFilesFromXml(ref installerToUpdateList))
            return;            

       //some code
    }

As you can see, i have some functions which check correctness of input values or just have "try-catch" operators inside, and if "catch" case happens or input is not valid further execution of caller (Login_Button_Click function) should be prevented.
But all functions returning "bool" aren't look right as i think.

Is there any other ways to prevent calling function from further execution?

Upvotes: 1

Views: 242

Answers (1)

sydan
sydan

Reputation: 298

I would invert the Boolean conditions:

private void Login_Button_Click(object sender, RoutedEventArgs e)
{
    if (CheckFields() && WritePerforceSettingsXml(rewriteSettingsCheckbox.IsChecked.Value))
    {
        Dictionary<string, string> installerToUpdateList = new Dictionary<string, string>();
        if (GetUpdateListFilesFromXml(ref installerToUpdateList))
        {         
            //some code
        }
    }
}

This way you're checking positively which is clearer and easier to follow, you also reduce the number or returns in a function which increases readability. The code also has less lines.

Upvotes: 1

Related Questions