Refactoring TryParse Into a Value Object
Recently I worked with a colleague on some code using decimal.TryParse() and tried to find a better way of using it. Specifically I had a string value representing a currency amount entered by a user in a web form. The amount needed more than just normal validation, so I needed to do some stuff with it.
Here’s the code I started with:
public void SomeMethod(string userEnteredAmount){decimal amount;if(decimal.TryParse(userEnteredAmount, out amount) {//Do some stuff with amount}else {//Show message to user about invalid amount}}
I’ve recently found many cases where I find the use of Value Objects to be very applicable. I found this case to be a particularly interesting example. Anyway, I created a Value Object called Amount to abstract away the TryParse stuff. Below is the class I created.
public class Amount{private readonly decimal _value;private readonly bool _isValid;public Amount(string amount){_isValid = decimal.TryParse(amount, out _value);}public decimal Value{get { return _value; }}public bool IsValid{get { return _isValid; }}}
See how clean it got? At least I think so. The important part though is that it’s usage is so much easier to understand and read:
var amount = new Amount(userEnteredAmount);if(amount.IsValid) {//Do some stuff with amount.Value}else {//Show message to user about invalid amount}
It’s more code, but cleaner. Or did I say that already? :-) And of course it’s reusable other places where amount has a meaning.
