tags:

views:

78

answers:

3

Consider a standard ASP.NET web application where the user types in some numeric data on a form. On submitting, some business objects are spun up to operate on the numeric data. But server-side textbox controls in .Net return a value of type string. Question: Should the codebehind of the page take responsibility for parsing the strings into numeric data (and throwing errors if invalid), or should the business objects accept strings for their input and parse them themselves?

+3  A: 

IMO, the business objects should accept numeric types only. Strings can be parsed in various formats, according to culture specific rules. Numbers are numbers. You don't want to change your business objects for localization - accepting only numbers will make it easier to reuse.

Tom Ritter
I agree, make users enter correct data.
nportelli
Well, I disagree with "make users enter correct data". Users should be able to enter data anyway that makes sense to them, and the app should, if possible, make sense of it: Hence "2125551212", "212 555 1212", "(212)555-1212" "212.555.1212" should all be accepted as viable phone numbers.
James Curran
I sometimes think that "make users enter correct data" can be interpreted in different ways. For instance, the best widgets I've seen for entering phone numbers are textboxes which automatically inserts brackets and hyphens as you type - maybe that's more like "help users enter correct data" though.
mmacaulay
@mmacaulay: depends. Will that widget let me paste a formatted phone number into it? (MSAccess has a formatting widget like you describe, and I'm endlessly annoy that I can't paste into it.)
James Curran
@James - I'd consider it a bug if I couldn't paste into it. The one I'm most familiar with is a web application for controlling my VOIP phone. I just checked and it does let me paste in phone numbers.
mmacaulay
A: 

The business objects should only be given properly parsed & verified objects.

Now, should this parsing & verification be done in the codebehind? hard to say, as the codebehind really isn't a layer. Properly, the codebehind should just handle UI issues, and parsing should be done at the controller layer between UI & business. However, most people just stick the controller into the codebehind.

James Curran
+1  A: 

Generally you want your business logic to accept the types it works with, its clearer that way. Formatting your incoming data and validating it before you get to the business logic is a good practice as you aren't actually doing work on the data but preformatting it for the Business layer to work with. This especially helps when the input fails validation, you have less to step through to get it back to the user.

Jeremy B.