I’ve spent the last week at the Microsoft 2008 MVP Summit. It was a fantastic learning and sharing experience. Microsoft took excellent care of us the entire week. Spending time with other MVP’s and meeting my friends from all over the globe was priceless.
I also spent a good deal of time out of the classroom with members from four different teams. It was during these times that we had some very healthy, animated discussions on topics that we are both passionate about. In the end, we shook hands and parted with deep respect looking forward to our next discussion.
I don’t know about the readers of my blog, but I like passionate discussions. I like to listen to other developers explain their approaches to problem solving and their solutions. After the flamethrowers are put back in the armory, I then like time to think about why the other side was presenting their point of view. Many times the “why” never comes out in the dialog. That developers life experience normally does not get presented as part of a discussion on the .NET Framework. So I like to marinade on the facts and work backwards to try to get inside the other persons world to understand why they want to adopt this solution. This is known as inductive study. By asking questions of the facts presented, you can many times determine context and then come to an understanding or appreciation of the process that lead to their solution.
The Scenario
I spent several hours talking about the concept of business objects throwing exceptions in the property setters if the value did not pass the validation rules for that property. If you have read my latest article, WPF Business Application Series Part Three you know that I strongly favor using the IDataErrorInfo interface for business object validation broken rule notification as opposed to throwing exceptions from property setters.
I thought long and hard about the discussions and came to this conclusion, you either favor the Fort Knox or Shopping Cart approach to business object validation. One is a controlling paradigm the other a trusting relationship. One takes a very granular approach the other a holistic approach to business object validation.
In discussions, business object validation is normally centered around UI binding scenarios. This is only one scenario and I would strongly argue that more validation takes place in the business layer processing of objects than direct UI binding. So proponents of throwing exceptions as a form of broken validation rule notification, must take a step back and look at this notificaiton business from a much higher perspective than just a UI binding scenario.
I realize that there are two schools of thought here. One states, an object should never be in a invalid state. The other, allows for temporary broken rules, but verifies object state prior to any actual use of the invalid object. This notion of absolute control or pure objects is an illusion that does not play well with real world business objects and today’s computer users. Of course application scope and requirements must dictate how and when business rules are enforced. As an architect I don’t want the platform to force me to write objects in a certain way just to utilize it, especially when there is no payback and only complicates development and code maintenance. Framework developers are not responsible for my data, me and my developers are.
WPF is one example of permitting developers to choose a broken validation rule notification technique that suits their application. It allows developers to use exceptions or IDataErrorInfo for broken validation rule notification to the class binding to it.
Fort Knox Business Layer Problem
The Fort Knox approach can kill business layer code like LINQ queries that attempt to populate that object and the data is invalid for one reason or another. I’ll use two examples to illustrate this problem.
If you have validation rules that are dependent on one or more property values, developers will now have to write code to set property values in a certain order to avoid an exception being thrown. This is a crazy requirement and is contrary all .NET class design documentation. Can you imaging having to wrap EVERY piece of code that sets a property with a try catch block. Again, what about LINQ queries that are tying to populate objects and unnecessary exceptions are being thrown by property setters. This makes writing maintainable code MUCH harder and with ZERO payback. When code is changed over time, a field added, we have to factor in usless exception handling and be cognasent of the order in which property setters are called or change.
I was speaking to one of the team PM’s on Friday. When I asked him about a certain issue his response was, “stuff happens.” I agree with him, stuff does happen. The Fort Knox approach does not allow for (actually tries to prevent) temporary invalid object state. This all comes full circle to the Fort Knox developers that some how get this false sense of security from exceptions being thrown, as opposed to developers checking an object’s Error property or other properties that expose object state and collections of broken validation rules. Any developer can read and learn this programming pattern from Rockford Lhotka’s CSLA, Microsoft’s Validation Application Block or Karl Shifflett’s Lightweight Business Object Declarative Programming.
Using the Fort Knox approach does not guarentee a valid object either. The developer could go through the pains of catching exceptions, but the object is still invalid if it does not pass all the validation rules.
In reality both approaches do allow for tracking broken rules since the developer is free to write any code in each setter and then throw the required exception. My biggest problem is having to code around what should be a reporting problem. However, this still means that all business layer processing code would have to be on the look out for a broken validation rule exception each time a setter was accessed as opposed to business layer code checking the object validation state as a whole, prior to persisting or moving an object to another tier.
Close
I welcome your feedback on this topic. Please comment on your approach to business object broken validation rule notification. Good discussions lead to better programming techniques and educate all who participate.
Have a great day!
Just a grain of sand on the worlds beaches.




April 20, 2008 at 2:07 pm |
Using exceptions seems just wrong to me. I agree that the IDataErrorInfo implementation is a better solution, particularly for smart client applications. It does require checking the validity, particularly before saving, but that is a requirement I’m willing to accept. Exceptions are just too costly, Besides, they should only be used in exception cases. If you know ahead of time that a user might try to supply a value that is out of range, this is an expected behavior, not exceptional one. In this case, I fall back to my exception rule of thumb: “Don’t pee your pants to see if your fly is open.”
April 20, 2008 at 2:44 pm |
yes, using exception is fundamentally wrong for business rule validation, both from design/implementation principle and run-time performance.
using exception in property get/setter is another design violation, should keep the implementation in property getter/setter lightweight as possible as we can.
In this context, validation is a business concern.
April 20, 2008 at 2:51 pm |
in my current system, there is a requirement to allow certain user roles save (in)valid objects along with validation results into system – override validation warnings and errors. using exception approach is going to be very hard to implement such requirement.
April 20, 2008 at 3:12 pm |
Thank you both very much for your informative feedback. Have a great day!
Karl
April 20, 2008 at 11:57 pm |
I don’t think that exceptions should be thrown from property setters on your business objects. Never. No ifs, ands, or buts. No there isn’t an *ahem* exception to the rule. I know that the Framework Design Guidelines say it’s acceptable, but it’s really not.
Karl’s point regarding LINQ is a perfect example. I am a huge fan of the object initializer syntax and would be quite ticked off if I had to wrap my initializer in a try/catch block because someone thought that ever property I set deserved some form of validation. And let’s not get into the world of multi-step validation dependencies (the valid values of property A, depend on the values of property B, which depends on C whose validation depends on A). No, no and no some more! I would extend the FDG’s advice of moving complex logic that might be exceptional out of property getters into a separate method to include setters as well.
In a worse case scenario, I ran into a validation bug once that had me scratching my head for about an hour. I checked a box on the UI that fired of a series of checks travelling up the hierarchy and back down again and because object didn’t validate (yes not just the property but the entire object was validating itself) immediately unchecked itself with no indication why. Buried deep within that chain of validation was a check of a setting to prompt the user when the validation failed. That setting was false so it just silently rejected the change. Most of the validations that were occuring had nothing to do with the particular piece of functionality I was debugging.
This experience made me a firm believer that validation does not belong on your business objects…at least not on the property setters. Some people prefer to put business methods on their business objects. It’s not my preferred style, but I don’t see it having the same pitfalls as global “validation” because what’s invalid in one scenario might not be in another (what happens when your requirements tell you that you need to allow a user to save his work in progress without committing it…will you force the user to get his work to a “valid” state before he can save for later?)
Just my two cents.
April 21, 2008 at 5:00 pm |
Not a fan of the property setter validation at all. To me this is really UI level validation. Because in the property setter you really can’t depend on the value of other fields(without standing on your head). So the only validation you can reliably do in the setter should be done in the UI. For example is it a valid date, number, etc. Also depending on you UpdateSourceTrigger the value sent to the setter may not be valid yet. So the setter really doesn’t work to well.
I now I said a bad thing, validation rules in the UI. While I believe all errors should be validated in the Business layer(BL). Some should also be implemented in the UI to prevent the round trip back to the BL when appropriate. For example a invalid date or a letter in a number textbox shouldn’t need to go back to the BL to determine that. It should be trapped in the UI and verified later in the BL.
I use custom attributes on each property on my BO to notify the UI how to handle each property accordingly. This keeps the rules in the BL but lets the UI do its job too.
April 21, 2008 at 7:47 pm |
Rocko,
I place my validation on BLL object property using attributes also. Have been thinking about sending them to the UI at run time.
But I believe there is a need for BLL objects to provide other BLL objects the ability to test an object before persisting the object or moving it to another tier.
I have received many emails and thank everyone that has posted so far. Not a single vote for throwing exceptions from setters. Hummm…
Cheers,
Karl
April 21, 2008 at 9:52 pm |
[...] Fort Knox Business Objects ( yes / no ) – Karl Shifflett On data validation strategies [...]
April 23, 2008 at 7:35 pm |
I believe all business validation logic should be written in binary.
BTW – your writing style has vastly improved. Keep up the great work!
April 23, 2008 at 9:03 pm |
Josh,
Thank you for the encouragment and mentoring! Wouldn’t be here without you.
Best to you always,
Karl
February 2, 2009 at 9:29 pm |
>> Not a single vote for throwing exceptions from setters. Hummm…
Okay, I’ll bite. Before I do, though, Karl, let me say that I attended and greatly enjoyed your presentation this past weekend in Cupertino. You are most entertaining, and I like your “show me” approach to architecture. There are, in this business, far too many eggheads constantly trying to one-up each other and grab the title of Smartest Guy on the Planet, and you did not strike me as aspiring to that regrettable fraternity, for which I thank you. (Even if there is a Smartest Guy on the Planet, I just don’t care!)
Now for the discussion of property setter exceptions…
I think most of us probably agree that validation rules are business logic, and that business logic should reside in the model rather than in the UI. We probably mostly agree, also, that invalid data should not be allowed into the permanent data store. What there does not seem to be agreement about here is whether invalid data should be allowed in our in-memory (or otherwise not-yet-persisted) business objects…or for how long.
The objections you and others here have raised to throwing exceptions in property setters seem to be these:
>>
“If you have validation rules that are dependent on one or more property values, developers will now have to write code to set property values in a certain order to avoid an exception being thrown.”
<>
…what about LINQ queries that are tying to populate objects and unnecessary exceptions are being thrown by property setters.
<>
However, this still means that all business layer processing code would have to be on the look out for a broken validation rule exception each time a setter was accessed as opposed to business layer code checking the object validation state as a whole, prior to persisting or moving an object to another tier.
<>
[rockowpb says...]
Because in the property setter you really can’t depend on the value of other fields(without standing on your head). So the only validation you can reliably do in the setter should be done in the UI. For example is it a valid date, number, etc.
<>
[mdizzy says]
Karl’s point regarding LINQ is a perfect example. I am a huge fan of the object initializer syntax and would be quite ticked off if I had to wrap my initializer in a try/catch block because someone thought that every property I set deserved some form of validation.
<<
To whom, exactly, do you wish to offload the work of getting the values you have decided to set into a valid state? Are you just guessing at the values? If you don’t really know what the values should be, why are you setting them?
February 3, 2009 at 9:37 pm |
Thank you for your kind remarks on the presentation.
Good response to exceptions in property setters. In the end, it comes down to what the developer wants and will support over time.
This is one point of contention where very little “gray” separates the two camps.
Got to love software!
Have a super day and thank you!
Karl
February 5, 2009 at 2:49 pm |
My previous post got garbled. Since I composed it in Word originally I’m going to try submitting it again, but with out the double greater than / less than signs in case those caused a problem.
February 5, 2009 at 2:52 pm |
** Not a single vote for throwing exceptions from setters. Hummm…
Okay, I’ll bite. Before I do, though, Karl, let me say that I attended and greatly enjoyed your presentation this past weekend in Cupertino. You are most entertaining, and I like your “show me” approach to architecture. There are, in this business, far too many eggheads constantly trying to one-up each other and grab the title of Smartest Guy on the Planet, and you did not strike me as aspiring to that regrettable fraternity, for which I thank you. (Even if there is a Smartest Guy on the Planet, I just don’t care!)
Now for the discussion of property setter exceptions…
I think most of us probably agree that validation rules are business logic, and that business logic should reside in the model rather than in the UI. We probably mostly agree, also, that invalid data should not be allowed into the permanent data store. What there does not seem to be agreement about here is whether invalid data should be allowed in our in-memory (or otherwise not-yet-persisted) business objects…or for how long.
The objections you and others here have raised to throwing exceptions in property setters seem to be these:
**
“If you have validation rules that are dependent on one or more property values, developers will now have to write code to set property values in a certain order to avoid an exception being thrown.”
**
Simply not true.
If your validation rule addresses the relationship between the values of two different properties, then you can’t property attempt to enforce it in a property setter. For example, suppose I have two integer properties, and that property B should always have a larger value than property A. I can’t enforce this rule in the setter for either property, because I don’t know what’s in the user’s head. Maybe she means to change both values. I have to give her the chance to do that. I can only sensibly enforce this rule when I validate the entire object (as I might do before permitting it to be saved or even navigated away from).
But none of that says I shouldn’t enforce any sort of rules in property setters. If I know that a particular property’s value should never be greater than 100, independent of the state of any other property or object, then why not enforce that rule in the setter? It is the most elegant place to do it. When I enforce it there, I don’t have to depend upon any other part of the application being written in such and such a way. With that one simply device I can guarantee that the value of that particular property will never cause a problem anywhere in my app (or any other app that retrieves it from the data store) because it’s out of range.
**
…what about LINQ queries that are tying to populate objects and unnecessary exceptions are being thrown by property setters.
**
What special issues arise from the use of LINQ queries? If a particular type of object is required to have a certain state before it can be used, then who cares what means are used to create or update it? The rules are the rules. If valid means something different at the time an object is created than at the moment it’s saved to the database, then the rules should simply be written to consider the context.
**
However, this still means that all business layer processing code would have to be on the look out for a broken validation rule exception each time a setter was accessed as opposed to business layer code checking the object validation state as a whole, prior to persisting or moving an object to another tier.
**
I believe feedback about a problem should be given to the user at the earliest possible moment. It’s usually much easier for the user to correct a mistake immediately after they’ve made it than an hour and 17 changes of context later. It’s also easier to communicate to the user what the problem is when she is still operating in the context where the problem was introduced.
Naturally you (the developer) must wait to diagnose a problem until all necessary information for the diagnosis is available. Just as you can’t perform a multi-property validation in a single property’s setter, you also wouldn’t want to tell the user she’s entering an invalid string value before she’s finished typing the string.
**
[rockowpb says...]
Because in the property setter you really can’t depend on the value of other fields(without standing on your head). So the only validation you can reliably do in the setter should be done in the UI. For example is it a valid date, number, etc.
**
What if an invalid date, number, etc., is set in non-UI code?
**
[mdizzy says]
Karl’s point regarding LINQ is a perfect example. I am a huge fan of the object initializer syntax and would be quite ticked off if I had to wrap my initializer in a try/catch block because someone thought that every property I set deserved some form of validation.
**
To whom, exactly, do you wish to offload the work of getting the values you have decided to set into a valid state? Are you just guessing at the values? If you don’t really know what the values should be, why are you setting them?
February 6, 2009 at 4:10 am |
gdunn,
Again, good points. Developers need to fully understand their systems and requirements.
My view on the subject is still strongly against throwing exceptions from property setters because of validation rule violations. But I do respect other developers design to do things differently.
Cheers,
Karl