Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When to return result vs throw exception? #9

Open
Hapachino opened this issue Aug 5, 2020 · 1 comment
Open

When to return result vs throw exception? #9

Hapachino opened this issue Aug 5, 2020 · 1 comment

Comments

@Hapachino
Copy link

Hapachino commented Aug 5, 2020

Hey Vladimir,

Big fan and thanks for the course!

Per the title, I'm a little confused when you were returning Results versus throwing exceptions. From your previous content, I believe your stance boils down to return Results for expected errors, and throw exceptions representing programmer errors or ones that can't be handled.

Customer.promote throws when already promoted, even though this is an error we expect and can handle. Unless the programmer error is he didn't check canPromote beforehand. Similarly, the value objects used factory methods return Results with input validation, but the Customer constructor throws with invalid arguments. The implication is the programmer has to validate the name and email before calling the Customer constructor.

This feels a little inconsistent and breaks encapsulation. I wonder if you still completely agree with the code here, and if so, how you would formalize this heuristic? Should value objects comprising an entity provide input validation via Results, while entities should throw errors to protect their invariants?

Thanks again.

@vkhorikov
Copy link
Owner

Unless the programmer error is he didn't check canPromote beforehand.

Yes, that's exactly the error here, it's part of the contract the programmer violates. Take a look at this article: https://enterprisecraftsmanship.com/posts/code-contracts-vs-input-validation/
I wrote about the pattern itself here: https://enterprisecraftsmanship.com/posts/validation-and-ddd/

The same is true for the Customer constructor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants