私はいくつかのチームコードを見直していて、次のようなものを見つけました:
MyObj obj = null;
try {
obj = myService.findObj(objId)
} catch (MyObjNotFoundException e) {
// The object wasn't found, it's the "normal" path
// Here they create the object in DB (but don't touch the obj variable)
// There is about 60 line of code
}
if (obj != null) {
// The object already exist, logs are written and some queue is filled
// with current objId to be processed later on
}
私のレビューでは、 を使用Exception
して通常のプログラム フローを制御することは、パフォーマンスや保守性の点で良い考えではないことを書きます。null
最良の方法は、例外をスローする代わりに返すようにサービスを変更することですが、次のようになります。
- 彼らがサービスを所有しているかどうかはわかりません (別のプロジェクト/チームである可能性があります)
- 彼らは本当にこの例外を別の場所で必要とするかもしれません
したがって、例外をスローしない限り解決されないパフォーマンスの問題は別として、「よりクリーンな」コードを提供したいと思います。
サービスがこの Exception のみを送信することを知っている私の考えは次のとおりです。
try {
obj = myService.findObj(objId)
} finally {
}
if (obj == null) {
// The object wasn't found, it's the "normal" path
} else {
// The object already exist, logs are written and some queue is filled
// with current objId to be processed later on
}
あなたはこの道を行きますか?それは本当に読みやすさへの一歩を踏み出しますか? 何か他のことを考えますか?
どうもありがとう。