views:

35

answers:

1

I have seen plenty of online guidelines for authoring extension methods, usually along these lines:

1) Avoid authoring extension methods when practical - prefer other approaches first (e.g. regular static methods).

2) Don't author extension methods to extend code you own or currently develop. Instead, author them to extend 3rd party or BCL code.

But I have the impression that a couple more guidelines are either implied or advisable. What does the community think of these two additional guidelines:

A) Prefer to author extension methods to contain generic functionality rather than application-specific logic. (This seems to follow from guideline #2 above)

B) An extension method should be sizeable enough to justify itself (preferably at least 5 lines of code in length).

Item (B) is intended to discourage a develoer from writing dozens of extension methods (totalling X lines of code) to refactor or replace what originally was already about X lines of inline code. Perhaps item (B) is badly qualified, or even misinformed about how a one line extension method is actually powerful and justified. I'm curious to know. But if item (B) is somehow dismissed by the community, I must admist I'm still particularly interested in feedback on guideline (A).

+2  A: 

The Microsoft Guidelines are a good place to start. The major addition to your points is that you should employ class inheritance to extend functionality if that option is open - extension methods if not.

Jesse C. Slicer
I think your point approximately reinforces items (1) and (2) I listed. And perhaps you feel that reinforcement covers item (B) I proposed. But what about item (A)? Jury out?
Brent Arias
I would tend to agree with (A). Extension methods should solve framework-esque gaps rather than application gaps, as chances are greater that you have app-level code under your direct control (and thus can modify and/or extend via inheritance) where for frameworks, there is less of a chance of that.
Jesse C. Slicer