27 April 2007

Transforming Conditionals

Testing conditions is at least 50% of code in a typical program. When developer writes code, he not always knows in advance how method will look like at the end. Let's look at some typical cases.

This one is pretty simple method, which takes care of null object:

    public string ConvertToString(object obj)
    {
      if (obj != null)
        return obj.ToString();
 
      return null;
    }

Then I decided to add special handling for IConvertible:

    public string ConvertToString(object obj)
    {
      if (obj != null)
      {
        IConvertible convertible = obj as IConvertible;
        if (convertible != null)
          return Convert.ToString(convertible);
 
        return obj.ToString();
      }
      return null;
    }

Now it seems that it would have been better idea to check and return null immediately instead of placing all the code in the block. How can we fix this? I put caret on an "if" keyword and hit Alt-Enter.



After context action is executed I get what I need:

    public string ConvertToString(object obj)
    {
      if (obj == null)
        return null;
      IConvertible convertible = obj as IConvertible;
      if (convertible != null)
        return Convert.ToString(convertible);
 
      return obj.ToString();
    }

If you like shorter methods, you can further transform the code:



Accepting convertion to conditional makes it even smaller:

    public string ConvertToString(object obj)
    {
      if (obj == null)
        return null;
      IConvertible convertible = obj as IConvertible;
      return convertible != null ? Convert.ToString(convertible) : obj.ToString();
    }



Note: Some or all of the features mentioned in this article may be available only in latest EAP versions of ReSharper.

No comments: