Wednesday, 7 January 2009

Evil Extension Method, or just handy?

 

I just realized I can have the following extension method:

   1: public static class StringExtensions
   2: {
   3:     public static bool HasContent(this string self)
   4:     {
   5:         return !string.IsNullOrEmpty(self);
   6:     }
   7: }

And then use it like this:

   1: [TestFixture]
   2: public class StringExtensionMethodsTest
   3: {
   4:     [Test]
   5:     [Category("Unit")]
   6:     public void TestStringHasContentWorksForNullStrings()
   7:     {
   8:         string s = null;
   9:         Assert.IsFalse(s.HasContent());
  10:     }
  11:  
  12:     [Test]
  13:     [Category("Unit")]
  14:     public void TestStringHasContentWorksForEmptyStrings()
  15:     {
  16:         string s = "";
  17:         Assert.IsFalse(s.HasContent());
  18:     }
  19:  
  20:     [Test]
  21:     [Category("Unit")]
  22:     public void TestStringHasContentWorksForStringsWithContent()
  23:     {
  24:         string s = "content";
  25:         Assert.IsTrue(s.HasContent());
  26:     }
  27: }

The interesting part is that a method call on a null object for an extension method works, which allows for the s.HasContent() idiom, instead of string.HasContent(s).

My question is the following: is relying on such “detail” good, in the way that it allows for less line noise and cleaner code, or bad for violating the idea that you can call a method on a null object and not get an exception?

I’d love to hear opinions on this.

No comments: