Should a business rule violation throw an exceptio

2019-03-12 21:16发布

Should a business rule violation throw an exception?

14条回答
疯言疯语
2楼-- · 2019-03-12 21:23

Business rules should not throw an exception, unless they are used to validate parameters of some API (i.e.: checking requests validity) or in unit tests (i.e.: using business rules to simplify .NET unit tests).

Generally business rules output error and warning messages to the validation scope, though.

查看更多
Fickle 薄情
3楼-- · 2019-03-12 21:23

Business rules could throw exception but they shouldn't.

If you have another way to communicate information about common and predictable validation error, you should use it.

查看更多
仙女界的扛把子
4楼-- · 2019-03-12 21:28

As an alternative view to most of the answers...

It can be useful to throw exceptions from the business logic, particularly if they are cuased by a failure in validation. If you are expecting an object and you get a null, it suggests that some problem has evaded detection in the user interface (or other interface). It may be completely valid to throw exceptions at this point. Indeed, you may decide to place this type of validation in the business logic when there are multiple interfaces.

Throwing exceptions in some languages / frameworks (I am thinking .NET) can be costly but this should not immediately worry you. It does mean that, at the name suggests, they are used for exceptional circumstances and not as part of the standard flow of a program. You certainly shouldn't throw an exception just to exit a method. You should also consider a graceful recovery where possible that may not include throwing an exception.

So, summing up... It depends...

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-03-12 21:30

Usualy I put the condition in a Specification object that implements

bool IsVerfiedBy(T entity);

So you can check the condition without exception.

If there is a place in your code where the specification should be verified beforehand, you can throw an exception because this is a prerequisit of you function.

For instance if your entity must be in a specific state before persistance, throw an exception when the specification is not verified, but use the specification before persisting so that the exception does not happen.

查看更多
我想做一个坏孩纸
6楼-- · 2019-03-12 21:30

There is good guidance in the wiki for the book 97 Things Every Project Manager Should Know, in particular in the chapter Distinguish Business Exceptions from Technical.

So, if your programming language supports it, the best thing is to create custom exception classes so the their workflow and handling can be different from technical exceptions.

查看更多
淡お忘
7楼-- · 2019-03-12 21:31

No Violating a business rule is a BUSINESS issue where an exception is a technical one. Violating a business rule is something that the system should regard as normal operation and for which it should have a programmed response, not an exception.

查看更多
登录 后发表回答