制御フローに例外を使用することは悪い習慣だと聞きました。これについてどう思いますか?
public static findStringMatch(g0, g1) {
int g0Left = -1;
int g0Right = -1;
int g1Left = -1;
int g1Right = -1;
//if a match is found, set the above ints to the proper indices
//...
//if not, the ints remain -1
try {
String gL0 = g0.substring(0, g0Left);
String gL1 = g1.substring(0, g1Left);
String g0match = g0.substring(g0Left, g0Right);
String g1match = g1.substring(g1Left, g1Right);
String gR0 = g0.substring(g0Right);
String gR1 = g1.substring(g1Right);
return new StringMatch(gL0, gR0, g0match, g1match, gL1, gR1);
}
catch (StringIndexOutOfBoundsException e) {
return new StringMatch(); //no match found
}
したがって、一致するものが見つからない場合、intは-1になります。これにより、部分文字列を取得しようとすると例外が発生しますg0.substring(0, -1)
。次に、関数は一致するものが見つからないことを示すオブジェクトを返すだけです。
これは悪い習慣ですか?各インデックスを手動でチェックして、すべてが-1であるかどうかを確認することもできますが、それはもっと手間がかかるように感じます。
アップデート
try-catchブロックを削除し、次のように置き換えました。
if (g0Left == -1 || g0Right == -1 || g1Left == -1 || g1Right == -1) {
return new StringMatch();
}
各変数が-1であるかどうかを確認するか、ブール値を使用foundMatch
して追跡し、最後に確認するか、どちらが良いですか?