How the ternary operator cleaned up my code

I had some code that was in Github for a pull request and Warren picked it up and added a few comments. One of the comments was

" You repeat this line on 58, perhaps just have the if/else set the value of cleanedProductPrice and then have the return outside of the if/else.

Additionally if you prefer you could then make the if into a ternary"

So I had a think and implemented the suggested changes. My code went from :

  if (decimal.TryParse(Product.Price?.Replace("GBP", string.Empty), out decimal price))
  {
      var cleanedProductPrice = string.Empty;
      if (price % 1 == 0)
      {
           cleanedProductPrice = price.ToString("0");
          return $"{Product.Name} {(string.IsNullOrWhiteSpace(Product.Price) ? "" : " - £" + cleanedProductPrice)}";
      }
      else
      {
           cleanedProductPrice = price.ToString("0.00");

      }
      return $"{Product.Name} {(string.IsNullOrWhiteSpace(Product.Price) ? "" : " - £" + cleanedProductPrice)}";
  }
  return string.Empty;

To this version :

if (decimal.TryParse(Product.Price?.Replace("GBP", string.Empty), out decimal price))
{
    var cleanedProductPrice = price % 1 == 0 ? price.ToString("0") : price.ToString("0.00");

    return $"{Product.Name} {(string.IsNullOrWhiteSpace(Product.Price) ? "" : " - £" + cleanedProductPrice)}";
}
return string.Empty;

This made a massive difference to the readability of the code but also reduced the duplicates.

I know I had duplication and I knew there was a code smell but at the time, I couldn't think how I could fix it. This is just one of the advantages of having constructive pull requests. It also gives me blog content.

Thanks Warren #h5yr

Published on : 04 April 2024