Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do you place your validation logic?

Tags:

c#

oop

How would you structure your code in the following scenario:

Several business objects (e.g.Person, House, etc), and between them, you need to validate the user inputs (which come in from textboxes). Would that go in either:

  1. Each business object
  2. The winforms codebehind
  3. A seperate (static?) class.

Thanks

like image 353
GurdeepS Avatar asked Mar 16 '26 11:03

GurdeepS


1 Answers

A very widely used approach, which I endorse in such scenarios, is to introduce the concept of a viewmodel: a class that aggregates all data to be displayed in a form, and which specifies (through attributes or some other mechanism) what type of validation should be performed on this data.

This approach has several benefits which include:

  • Decoupling the validation logic from your models (perhaps there are validation scenarios which you want to enforce today but are not inherent in your data itself); this way you are capable of defining distinct validation scenarios for distinct parts of your application where the same business objects come into play (e.g. in some part of the business logic each Person must have a Spouse, but having a Spouse is not an inherent property of every Person everywhere)
  • Decoupling the validation from the presentation logic (your view's codebehind); this way you are not forced to specifically tangle your presentation behavior with business object validation
  • Validation code being isolated and each part of it targets a specific type of validation only; this way, validation code can be reused across your application wherever it is applicable

The actual code that does the validation will typically be inside a separate validation class; your viewmodel would only dictate how each piece of validation should apply to each piece of data.

like image 191
Jon Avatar answered Mar 18 '26 00:03

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!