2013-03-14 22 views
5

私のプログラムはユーザーの入力を待って、適切な場合にはそれを処理します。私は、特定の基準を満たしているかどうかを確認するためにユーザー入力を確認する必要があり、それがすべての基準を満たしていない場合は却下されます。ユーザー入力にエレガントなエラーを確認してください

擬似コードのようなものです:

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文は仕事をする - しかし、これを行うために、一般的に良い方法はありますか?

+1

例外..... –

+0

最初に問題を引き起こした条件を正確に反映したtry-catchおよび例外クラスを使用して、マイナス条件チェックを検討しましたか? – WhozCraig

+0

入力がどの程度複雑になるかによって異なります。私は入力がどのように有効であるかを宣言するDSLを作成し、そのDSLを表すオブジェクトを作成し、この入力を検証するとします。 –

答えて

2

どの程度

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

その後、あなたの例外ハンドラは、エラーメッセージを報告し、再試行するか、必要に応じて中止することができます。

1

私はあなたが「早期復帰」技術を使用することができますお勧め:

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. 
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 
} 
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); 
関連する問題