Introduction
Once upon a time, I was diving into a new codebase and came upon an intriguing issue. StringTrim() calls polluted the entire codebase. I was taken aback. All user input, in my opinion, should be sanitized by calling at least the Trim function over all string properties. I discovered the problem root after digging a bit dipper. Users frequently copy and paste dates from local notebooks, communications, and so on. In addition, after selecting a string, it occasionally selects with surrounding space and newline characters.
As a result, a simple UserName field could be filled all possible ways:
- "John Doe "
- " John Doe"
- " John Doe "
- "John Doe"
Finally, separate program components treat this as if it were one or four different users. Simply because certain components clip spaces while others leave UserName alone.
One amusing (actually not) outcome appears to be a success story: a man registered to the internet business twice (with space difference in the userName). However, the login component treats usernames with and without a leading space as one user. The same is true for the payment subsystem. However, the order handling component sees two distinct users. As a result, the user places one order, pays once, and receives it twice. :-)
Solve the problem with one smart enough nuget Package
Soling this and similar situations as easy as pie. You should never trust user input and always remove leading and trailing spaces. Additionally it's a good practice to remove duplicate spaces inside the strings.
Recommended nuget package is: StringTrimmer
Usage is very simple. Just call TrimExtraSpaces() extension method over any user provided class. And this method automatically trim all public string properties.
public void CreateUser (User user)
{
user.TrimExtraSpaces(); // Just one line
}
P.S. All string properties are found and trimmed using reflection in this nuget package. This method is better than nothing, but it is not the quickest! To increase class properties trimming speed I'm working on Source Generated StringTrimmmer code.
StringTrimmerGenerator
Feel free to conact me and contribute to the project to make user input safer to use.
Top comments (0)