简体   繁体   中英

extension method call another in same extension class - good design?

i ask myself if it is a good design if an extension method uses another in the same extension class.

public class ClassExtensions
{
   public static bool IsNotNull<T>(this T source)
      where T : class
   {
      return !source.IsNull();
   }

   public static bool IsNull<T>(this T source)
      where T : class
   {
      return source == null;
   }
}

EDIT Thanks for the answers. And sorry for the bad sample.

It's fine. Your example is a little trivial, of course, but consider other situations where a method could provide overloads (using string.Substring as example... pretend method doesn't already exist).

public static class Foo
{
    public static string Substring(this string input, int startingIndex)
    {
         return Foo.Substring(input, startingIndex, input.Length - startingIndex);
         // or return input.Substring(startingIndex, input.Length - startingIndex);
    }

    public static string Substring(this string input, int startingIndex, int length)
    {
         // implementation 
    }
}

Calling overloads obviously allows you to keep your logic centralized as much as possible without repeating yourself. It is true in instance methods, it is true in static methods (including, by extension, extension methods).

IMHO, usually it is, as it reduces the amount of code you have to write and thus the chance to make errors.

In the above example, however, I think that it is overkill because of the simplicity of the method.

Yes, it is a good practice. Consider the class as a kind of a namespace and group related extensions together.

Sure it is a good design, and can be referred to as DRY .

This, however, is a very trivial example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM