Check data entry for errors

My program waits for user input and, if necessary, processes it. I need to check the user’s input to make sure that he meets certain criteria, and if he does not fulfill all these criteria, he will be rejected.

The pseudocode looks something like this:

if (fulfills_condition_1)
{
    if (fulfills_condition_2)
    {
        if (fulfills_condition_3)
        {
            /*process message*/
        }
        else
            cout << error_message_3; //where error_message_1 is a string detailing error
    }
    else
        cout << error_message_2; //where error_message_2 is a string detailing error
}
else
    cout << error_message_1; //where error_message_3 is a string detailing error

There is a possibility that the number of these conditions may increase, and I was wondering if there would be an easier way to represent this using a switch or something like that instead of a lot of cascading operators if.

I know there is an opportunity to use

if (fulfills_condition_1 && fulfills_condition_2 && fulfills_condition_3)
    /*process message*/
else
    error_message; //"this message is not formatted properly"

but it is less useful than the first, and does not say where the problem is.

, .. condition_1 , condition_3, if , ?

+5
4

if (!fulfills_condition_1) throw BadInput(error_message_1);
if (!fulfills_condition_2) throw BadInput(error_message_2);
if (!fulfills_condition_3) throw BadInput(error_message_3);

/* process message */

, .

+2

if s, :

:

bool is_valid = true;
string error = "";
if (!condition_one) {
  error = "my error";
  is_valid = false;
}

if (is_valid && !condition_two) {
  ...
}

...

if (!is_valid) {
  cout << error;
} else {
  // Do something with valid input
}

:

try {
  if (!condition_one) {
    throw runtime_error("my error");
  }

  if (!condition_two) {
    ...
  }

  ...

} catch (...) {
  // Handle your exception here
}
+2

" ":

  if (!fulfills_condition_1)
     // error msg here.
     return;

  // fulfills_condition1 holds here.

  if (!fulfills_condition_2)
     // error msg here.
     return;

  // Both conditon1 and condition2 hold here.

  if (!fulfills_condition_3)
     // error msg here.
     return.
+1

, DSL:

Validator inputType1Validator =
    Validator.should(fulfill_condition_1, error_message_1)
             .and(fulfill_condition_2, error_message_2)
             .and(fulfill_condition_3, error_message_3)

inputType1Validator.check(input);
+1

All Articles