views:

44

answers:

2

I want to be helpful to the users of a system, so I'll clean up the input a bit before testing if it can be used. So I have a flow like this:

  1. Input: aa12345b
  2. Clean input somehow: 12345
  3. Test if clean input is valid
  4. Use input if valid

Now I want to do this in a beautiful OO-fashion (IoC, interfaces, testable, no statics, you know). Any ideas how to organize a class structure for this? Is it good to have a Cleaner and a Parser/Validator class separately, or put them as methods in the data class itself? Thanks for any help or discussion about this, and extra thanks if the answer is in C#!

+3  A: 

I applaud you for thinking of thinking of ease of use. However, looking at your example, cleaning the input like this is a bad idea. You're assuming that you, as the programmer, know what the user meant to enter when they enter something invalid. This is not possible. You're better off using the tried-and-true method of displaying a helpful, friendly message from a standard validator, such as a Regular Expression Validator.

You have to assume that if the user entered the wrong thing, they either

  1. Mis-typed
  2. Didn't understand the input requirements
  3. Intentionally entered domething malicious looking for improper validation and hunting for vulnerabilities in your software in a preliminary investigation before attempting to hack it.

For options 1 or 3, you're better off giving a helpful message to the user and having them re-type the input. For option 3, you'd be encouraging a potential attacker by not using best practices.

David Stratton
Thank you for your answer, but assuming that the input (and output) is on a computer is incorrect in this case. This time it's about SMS and the input is very simple. Instead of annoying the user I will clean the input from obvious typos instead. So I understand and agree with your answer, but I need this feature. :)
ciscoheat
+1  A: 

I agree with David Stratoon, this isn't generally a good idea, but the choice is ultimately your.

I would personally write the methods as as extension methods for the String class. in that case your methods would show up as part of System.String instance methods.

InputTextbox.Text.ParseNumerics();


public static int ParseNumerics(this String str)
{
        //return parsed string
}

http://msdn.microsoft.com/en-us/library/bb383977.aspx

Keivan