优雅地检查用户输入的错误

Check user input for errors elegantly

本文关键字:输入 错误 用户 检查      更新时间:2023-10-16

我的程序等待用户输入,并在适当的时候处理它。我需要检查用户输入,以确保它满足某些标准,如果它不满足所有这些标准,它将被拒绝。

伪代码类似于:

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

这些条件的数量可能会增加,我想知道是否有一种更简洁的方式来表示这一点,使用开关或类似的东西,而不是大量的级联if语句。

我知道有可能使用

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

,但这没有第一个有用,并且没有说明问题在哪里。

条件可以大致按重要性递增排列,即检查condition_1比检查condition_3更重要,因此if语句确实有效-但是是否有更好的方法来实现这一点?

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 */

那么您的异常处理程序可以报告错误消息,并在适当的时候重试或中止。

如果您是级联的if s困扰,您可以选择以下之一:

使用boolean:

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
}

我建议你可以使用"提前返回"技术:

  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.

如果要在一些地方重用它,我会创建一个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);