I am using ASP.NET MVC 2 with nhibernate. I have this Sales class. Sales has many Payments. Sales’ payments should not be modified once the sales’ status becomes confirmed. I need suggestions on how to enforce this.
I’m stumped on several things when trying to put this validations:
- For adding and deleting payments:
- I can create AddPayment and DeletePayment methods in Sales, but everybody must remember to use these instead of adding and deleting the payments collection directly
- I don’t want to hide the payments collection because nhibernate needs it, also this collection is used in other parts of the software
- For modifying existing payments:
- I don’t think I should put the validation in the Payments setters because nhibernate needs to access the setters.
- Should I throw exception? There’s a discussion about the disadvantages of throwing exception to prevent object entering invalid state. In my case object state after modification may still be valid, but I want to block the modification. Is throwing exception reasonable in this case? What are the alternatives?
Should I enforce this in the controller actions?
You can hide the collection by making it protected or even private. NHibernate will still find it. Alternatively you could have the collection getter return an immutable collection when the sales status is the restricted value.
Putting validation rules in the setters is also fine. You can tell NHibernate to access the backing field directly (you may have to add a backing field if you’re currently using auto properties).
Edit for the additional question…
I don’t tend to throw exceptions until right before a save. Throwing them earlier, like in a property setter, can be annoying to UI developers who have to go back to the user with just one error at a time. I do mostly MVC applications too, so I’ve been using the System.ComponentModel.DataAnnotations validation attributes of late. While limited in some respects, they work well with MVC for the model checks at the browser and in the controller. If you use those, however, I recommend creating a custom interceptor to check them all right before a save. The interceptor is where I will throw an exception if anything is awry.