Should my repository enforce validity of data, if so, where and how?

I have a repository data access pattern like so:

IRepository<T> { .. query members .. void Add(T item); void Remove(T item); void SaveChanges(); }

Imagine the scenario where I have a repository of users, users have a user name which is unique, if I create a new user with a username that exists (imagine I have a dumb ui layer that doesn't check), when I add it to the repository, all is fine.. when I hit SaveChanges, my repository attempts to save the item to the database, my database is enforcing these rules luckily and throws me back an aborted exception due to a unique key violation.

It seems to me that, generally this validation is done at the layer ABOVE the repository, the layers that call it know they should ensure this rule, and will pre-check and execute (hopefully in some kind of transaction scope to avoid races, but doesn't always seem possible with the medium ignorance that exists).

Shouldn't my repository be enforcing these rules? what happens if my medium is dumb, such as a flat database without any integrity checks?

And if the repository is validating these kind of things, how would they inform callers about the violation in a way that the caller can accurately identify what went wrong, exceptions seem like a poor way to handle this because their relatively expensive and are hard to specialize down to a specific violation..

I've been playing around with a 'Can' pattern, for example.. CanAdd with Add, add will call CanAdd and throw an invalid operation exception if can returns a violation.. CanAdd also returns a list of violations about what went wrong.. this way I can start to stack these routines through the stack.. for example, the service layer above would also have a 'Can' method that would return the repositories report + any additional violations it wanted to check (such as more complicated business rules, such as which users can invoke specific actions).

Validation of data is such a fundamental yet I feel there is no real guidance for how to handle more advanced validation requirements reliably.

Edit, additionally in this case, how do you handle validation of entities that are in the repository and are updated via change tracking.. for example:

using (var repo = ...) { var user = repo.GetUser('user_b'); user.Username = 'user_a'; repo.SaveChanges(); // boom! }

As you could imagine, this will cause an exception.. going deeper down the rabbit hole, imagine I've got a validation system in place when I add the user, and I do something like this:

using (var repo = ...) { var newUser = new User('user_c'); repo.Add(newUser); // so far so good. var otherUser = repo.GetUser('user_b'); otherUser.Username = 'user_c'; repo.SaveChanges(); // boom! }

In this case, validating when adding the user was pointless, as 'downstream' actions could screw us up anyway, the add validation rule would need to check the actual persistence storage AND any items queued up to persist.

This still doesn't stop the previous change tracking problem.. so now do I start to validate the save changes call? it seems like there would be a huge amount of violations that could happen from aparently unrelated actions.

Perhaps I'm asking for an unrealistic, perfect safety net?

Thanks in advance, Stephen.

-------------Problems Reply------------

The ideal rule is that each of your layers should be a black box and none of them should depend on validation of another layer. The reason behind this is that the DB has no idea of the UI and vice versa. So when the DB throws an exception, the UI must have DB knowledge (bad thing) to convert that into something the UI layer can understand, so it can eventually convert it into something the user can understand. Ugh.

Unfortunately, making validation on every layer is also hard. My solution: Either put the validation in a single place (maybe the business layer) and make the other layers really dumb. They don't check anything elsewhere.

Or write your validation in an abstract way into the model and then generate all validation from that. For example:

String name;
Description nameDesc = new Description("name",
new MaxLength(20), new NotNull());

This way, you can write code which examines the Description stuff (generate code or even at runtime) and do the validation in each layer with little cost because one change fixes all layers.

[EDIT] For validation, you only have these cases:

  • Duplicate key
  • Above some limit
  • Below some limit
  • Null (not specified)
  • Empty
  • Formatting error (date fields, etc)

So you should be able to get away with these exception classes which have object, field, old&new value plus special info like the limit that was hit. So I'm wondering where your many exception classes come from.

For your other question, this is ... uh ... "solved" by the two phase commit protocol. I say "solved", because there are situations when the protocol breaks down and in my experience, it's much better to give the user a "Retry?" dialog or some other means to fix the problem rather than investing a lot of time into TPC.

Category:validation Views:0 Time:2009-03-31
Tags: validation

Related post

  • Symfony form validation for date fields (sfWidgetFormI18nDate) 2009-12-07

    I am using Symfony 1.2.9, and I have a form that contains two date fields: start_date AND end_date. I want to impose the following validation criteria for the 'start_date' field: i). CANNOT be less than todays date ii). CANNOT be greater than end_dat

  • Repository pattern with "modern" data access strategies 2010-11-12

    So I was searching the web looking for best practices when implementing the repository pattern with multiple data stores when I found my entire way of looking at the problem turned upside down. Here's what I have... My application is a BI tool pullin

  • Can you enforce that numeric data entered into a column not be a duplicated? 2014-09-23

    Can you enforce that numeric data entered into a column not be a duplicate of data currently in that column? I am not very familiar with VBA and apologize if this should be treated in a different forum. --------------Solutions------------- It doesn't

  • Which 'layer' is responsible for validation of data 2009-07-29

    Let say I devise an architecture like this - an application consists of modules and modules uses domain-specific utilities to perform changes to the model or database. An example, a registration module which shows the form, accept input and then use

  • CakePHP validation for dates 2009-09-10

    In CakePHP, is there a built-in way of validating a date to be within a certain range? For example, check that a certain date is in the future? If the only option is to write my own custom validation function, since it'll be pretty generic and useful

  • data validation for date data type in unix? 2009-12-10

    for eg if i m getting various inputs from keyboard ie Book accession number, Subject code Book_id , Author , Year of Publication, Title of the book, Publisher’s name, Price, and i want do validations such that year of publication must be before 1996,

  • How to in Git, clone a remote (GitHub) repository from a specifed date 2010-09-24

    I'm trying to clone a git repository from a certain date. Even if this is not possible. Is it possible to clone the git repository and then roll it back to a certain date? Example: my repository has been updated since May 2010, but I'd like to get th

  • Validating a date dd/mm/yyyy 2010-10-28

    Does anyone know of any good functions for validating a date via input text box in codeigniter like this: dd/mm/yyyy? Thanks --------------Solutions------------- You're probably looking for the strptime function. For the specified format you can use

  • Should Validation and Data Correction logic be done in business or data access layer? 2011-01-11

    So I have this general question of where should I have certain logic for example - var data=GetItems(); if(data==null) //return some defaults else return values //second case.. if(id<=0) //throw some exception else return id So should the above co

  • How do I enforce an expiration date for a trial install of my software? 2011-03-30

    I need to offer a trial period for my custom software. I have a 64-bit C# app, which uses 64-bit, multi-processor support DLLs. Other utilities to be included are written in C++ (exes and dlls). I must be able to encrypt the C# code, key the software

  • Regular Expression validator for date format DD/MMM/YYYY 2011-05-17

    <asp:TextBox ID="txtDob" runat="server" MaxLength="100" CssClass="textbox2" size="10" /> <ajax:TextBoxWatermarkExtender ID="txtWEDOB" WatermarkText="DD/MON/YYYY" TargetControlID="txtDob" runat="server" /> <asp:RegularExpressionValidato

  • javascript date validation using date object 2011-06-17

    According to, the date validation could be done using the javascript's date object. I've a similar scenario, where I have individual year,month,date in seperate text boxes which get validated

  • Validating a Data Driven Form in Silverlight 4? 2011-07-08

    I have a data driven form generated from database and using DataTemplateSelector for type of questions and I get a run time generated form. I would like to validate this form. The validation params are also in the db. I have not found any good exampl

  • Client Side Validation with Data Annotations in ASP.Net MVC3 2011-07-18

    I'm using ASP.Net MVC3 with VB. I have been able to get the server-side validation with data annotations working. Below is my relevant code: In my view model: <Required(ErrorMessage:="Last Name is Required.")> Public Property SearchLName() As S

  • How to pass validation error data through redirect()? 2011-10-28

    I have a page that contains a form and when any user submits it, the data goes to a controller and the controller checks the validation, if there is any error it redirects the user to the previous page( the page that contains the form), otherwise it

  • Symfony2 : Validating a date using the Form Validator returns error 2011-11-10

    I've added a element to my form which is of type 'date', this then has a validation rule which specifies that the form element value must be of type date, otherwise return an error. However rather than handling the validation, Symfony returns an Exce

  • Getting "no valid OpenPGP data found" When trying to add public key to Win 2003 server 2011-11-21

    I have been 'emailed' a list of public PGP Keys: development: "ssh-rsa AAASDHFhdfsdSDHF2SHdf932hSDF29SDFHSDF2SDFHSDF23SHDFewhw92sdfhSDFS29843SdhsdfZSDH= [email protected]" staging: "ssh-rsa AAASDHFhdfsdSDHF2SHdf932hSDF29SDFHSDF2SDFHSDF23SHDFewhw92sdfhSDFS298

  • Java-how to get the valid image data form a image? 2011-12-21

    I am a newer for java, now I need to write a software related with image process with java. I want to get the valid image data,for example:a bitmap named "abc.bmp", it include filehead, infohead, RGBquad and valid image data. What I want is just vali

  • custom model validation using data annotations MVC3 | error messages not shown on client side though properties are added and jquery written 2011-12-26

    I have implimented a custom validation using data annotation on model, MVC 3. Also imlimented jquery and scripts for unobstrusive client validation of the same, taken care to over ride the public override IEnumerable<ModelClientValidationRule>

Copyright (C), All Rights Reserved.

processed in 0.137 (s). 11 q(s)