Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it acceptable to use extension methods on a class which you can modify

I've recently been toying with the idea of using extension methods to implement helper utilities on classes which I control (ie, are in the same program and I can modify). The rationale behind it is that many times, these helper utilities are used in very specific scenarios and don't require access to the classes internal values.

For instance, let's say I have a StackExchange class. It'd have methods like PostQuestion and Search and AnswerQuestion.

Now, what if I wanted to manually calculate my reputation to ensure that StackOverflow isn't cheating me. I'd implement something along the lines of:

int rep=0;
foreach(var post in StackExchangeInstance.MyPosts)
{
  rep+=post.RepEarned;
}

I could add a method to the StackExchange class, but it doesn't require any internals, and it is only used from one or two other portions of the program.

Now imagine if instead you had 10 or 20 of these specific helper methods. Useful in a certain scenario for sure, but definitely not for the general case. My idea is changing something like

public static RepCalcHelpers
{
  public static int CalcRep(StackExchange inst){ ... }
}

To something like

namespace Mynamespace.Extensions.RepCalculations
{
  public static RepCalcExtensions
  {
    public static int CalcRep(this Stackexchange inst){...}
  }
}

Note the namespace. I'd ideally use this to group extension methods within a certain scenario. For instance, "RepCalculations", "Statistics", etc.

I've tried searching for if this type of pattern is at all heard of, and haven't found any evidence of extension methods being used for anything but classes you can't modify.

What shortcomings are there with this "pattern"? Should I instead stick to inheritance or composition, or just a good ol' static helper class for this?

like image 801
Earlz Avatar asked Dec 28 '12 16:12

Earlz


1 Answers

I would read the section of Framework Design Guidelines on Extension methods. Here is a post by one of the authors for the 2nd edition. The use case you are describing (specialized helper methods) is cited by Phil Haack as a valid use for extension methods with the drawback that it requires extra knowledge of the API to find those "hidden" methods.

Not mentioned in that post but recommended in the book is that the extension methods go into a separate namespace from the extended class. Otherwise, they will always appear with intellisense and there is no way to turn them off.

like image 196
Mike Zboray Avatar answered Sep 19 '22 16:09

Mike Zboray