How should one deal with invalid business objects in code?
Lets say that you have a business object whose current state implies that there is some kind of a bug in your code. Or basically any scenario where you are working with your own data but it is in a state that should never occur violating some rules. I like to typically check for such conditions and assumptions because it allows me to catch bugs early on closer to their source. However, what is the best practice if such a logic check fails?
I know that Debug.Assert statements are very handy for this, however I'm not very fond of them because they only appear in debug mode and not in the testing or release phase which can obviously still contain many such bugs. I'd much rather be informed that this check is failing as opposed to trying to debug a problem that occurs much 开发者_StackOverflow社区afterwards in the code. The solution to me looks like throwing an exception of some kind. Is this a good idea?
You're absolutely right, throw an exception.
You can extend the Exception class and use your extended version for these cases, this will let you handle them further up the chain for logging and halting the application if necessary.
try
{
}
catch(MyException ex)
{
ex.LogError();
if(ex.IsCritical)
throw ex;
}
I normally check for such problems in the business object itself and throw exceptions where ignoring would result in an object with invalid state. Such exceptions include (but are not limited to):
IllegalArgumentException
for arguments being passed in that are not acceptable (e.g. null where not allowed)IllegalStateException
for when the object may be driven into an incorrect state (distinct from the scenario where an argument is invalid)
As such the business object itself is never invalid.
I check for these situations immediately. The scenario I'm desperate to avoid is modifying an object such that it's in an invalid state, and only discovering this later (possibly years later - imagine serialising such an object and deserialising it a year from now). That would make discovery of the origin of such problems next to impossible.
I certainly want these checks to occur in production as well as development/testing phases. Normally the cost of performing such checks is negligible compared to the time taken for normal operation, and especially compared to the amount of time it would take you to revert from such a scenario.
Yes, this is the right way to do it in my opinion. The exception will bubble up and will not go unnoticed, allowing you to go back to the source of the problem.
精彩评论