Home > Software design >  How to avoid ifs on input entry
How to avoid ifs on input entry

Time:11-29

I have a question regarding IF s

I am checking the input from my user from entry and I wonder if I can somehow avoid too many ifs. I know this is not that many but I guess you get my point.

 if (string.IsNullOrWhiteSpace(OldPasswordEntry)|| string.IsNullOrEmpty(OldPasswordEntry))
                {
                    preparedToSubmit = false;
                    OldPasswordEntryValLabel = true;
                }

                if (string.IsNullOrWhiteSpace(NewPasswordEntry)|| string.IsNullOrEmpty(NewPasswordEntry))
                {
                    preparedToSubmit = false;
                    NewPasswordEntryValLabel = true;
                }

                if (string.IsNullOrWhiteSpace(NewPasswordConfirmationEntry) || string.IsNullOrEmpty(NewPasswordConfirmationEntry))
                {
                    preparedToSubmit = false;
                    NewPasswordConfirmationEntryValLabel = true;
                }

CodePudding user response:

The method IsNullOrWhiteSpace covers IsNullOrEmpty, but it also returns true if the string contains only white space characters.

 if (string.IsNullOrWhiteSpace(OldPasswordEntry) || string.IsNullOrWhiteSpace(NewPasswordEntry) || string.IsNullOrWhiteSpace(NewPasswordConfirmationEntry))
                {
                    preparedToSubmit = false;
                    OldPasswordEntryValLabel = true;
                }

or:

  OldPasswordEntryValLabel = (string.IsNullOrWhiteSpace(OldPasswordEntry) || string.IsNullOrWhiteSpace(NewPasswordEntry) || string.IsNullOrWhiteSpace(NewPasswordConfirmationEntry));
  preparedToSubmit = !OldPasswordEntryValLabel ;

CodePudding user response:

You could put the repetitive part into a function. Here a possible example, though it might be a bit more adapted to your needs:

bool preparedToSubmit = CheckPassword(oldPasswordEntry, out bool oldPasswordEntryValLabel) &
                 CheckPassword(newPassowrdEntry, out bool newPasswordEntryValLabel) &
                 CheckPassword(newPasswordConfirmEntry, out bool newPasswordConfirmationEntryValLabel);

bool CheckPassword(string value, out bool showLabel)
{
    if(string.IsNullOrWhiteSpace(value))
    {
        showLabel = true;
        return false;
    }
    showLabel = false;
    return true;
}
  •  Tags:  
  • c#
  • Related