开发者

what is preferred approach to return business validation results in business layer

Let's assume we have a client application (either web or standalone) which uses kind of business layer (EJB, Spring services etc). Let's say user wants to execute some business logic (e.g. create something). This operation has some preconditions like data format, existing of other objects in DB, permissions etc. Now what is the best design of this business logic layer, I mean how to return validation errors, indicate success, return unexpected error etc?

Ways I know:

1)

for validation errors return e.g. OperationResult object having status and list of violations,

for success: OperationResult with status=success and empty errors list,

for unexpected errors throw runtime exception

2)

for validation errors throw ValidationException (runitme or checked?) having list of violations

for success: void or created entity if required

for unexpected errors throw runtime exception

There are two basic ways I know but every time I start writing I have har开发者_运维技巧d time to get it right.


I have an aversion for the validation exception method, after all there is nothing exceptional in a validation error, so I find it hard to justify to use an exception for that. So on a theoretical basis the only valid option is the first one.

Having said that, although it depends on what validation framework you're using*, but it's usually much easier to code the exception version.

Whether your validation exception (if you're using one) should be checked or not opens up another can of worms, some people are very much against checked exceptions in general, others will say the exact opposite. For my two pennies worth I believe that runtime exceptions should be reserved for coding errors and an "expected" exception should be checked, whenever that's possible. But I have to stress that this is just personal preference on my behalf.

*If you have multiple validators that will all have to be run in a validation phase, exceptions are not very effective. If you intend to stop at the first failed validation step, exceptions are easier to implement and probably more readable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜