DEV Community

loading...

Discussion on: Where Do I Put My Business Rules And Validation?

Collapse
turnerj profile image
James Turner

Well written article! While I do like parts of the DDD concept, I'm not a fan of validation occurring on the creation of objects as it feels like one too many concerns for a constructor.

Take that final snippet in your post, the code doesn't actually read like it does any validation at all - it is just instantiating instances of objects. There is probably a case to say other objects do this too (eg. you can't create an instance of Uri that is invalid) but it just feels wrong (to me) having business objects like that.

That said, it does eliminate the case that validation is accidentally missed.

Collapse
ken473 profile image
Kenneth Mutombo

You summed it up well.

Collapse
jamesmh profile image
James Hickey Author

I would agree that in scenarios that are not very complex there's overhead to this too.

But it really shines whenever you start dealing with complex business problems.

Some people prefer to do something like this, but instead of doing validation in the constructor they will expose some Validate() method.

It's one of many tools 😂

Collapse
turnerj profile image
James Turner

One of the things I like in C# is actually the built-in validation system in the System.ComponentModel.DataAnnotations namespace. You can have basic things like whether a property is required or a string is meant to be an email address. You can easily add your own custom validation attributes too. There is a class called Validator in that namespace with a ValidateObject function which processes it all.

The validation doesn't need to be constrained to the attributes either because if your object implements IValidatableObject, then a Validate method on your object gets called too when using Validator.

Keep up the good articles 🙂

Thread Thread
jamesmh profile image
James Hickey Author

Thanks! I've seen people do that too.

There's always the discussion as to how much should be validated using ModelState in .NET etc. too.

I find it helpful, all things equal, to have the bulk of non-trivial validation located in the same place (inside the business logic - wherever that may be).

I've worked on a system that had to validate ALL business rules client-side, then in the app layer, and finally in the DB (stored procs).

So like the exact same business rules re-done in JS, C# and then TSQL. Really weird. But that's what they wanted!

I did learn about all 3 languages really quick 😂

Forem Open with the Forem app