do you use extension methods intensively in your projects?
-
Sander Rossel wrote:
On a few occasions I've created an interface, ISomething, and before writing any implementation I wrote a few extension methods I knew I needed.
Still doesn't make sense to me. If the interface is your own, you should write the method to the interface as it makes sense to be in its scope. If you need behavior without having to implement everywhere, you're looking for an abstract class. Extension methods provide a clean way to have helper methods to class you cannot modify. Otherwise you're just creating spaghetti code and killing a few principles. Although M$ does with it's own classes, it makes sense, specially to not break backwards compatibility when implementing new frameworks (like LINQ), so yes, they own the code, but they should not modify it, as LINQ is implemented in a whole different scope. If you are developing frameworks, with attachable components, that extend other standalone components, yes, it makes sense to have extension methods on your own code, otherwise I agree that's "silly".
To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia
I wholeheartedly disagree :D Extension methods are nothing more than static helper methods that are treated as instance methods by the editor (and the compiler?). I don't think there is a principle against creating static helper methods and it's certainly not creating spaghetti, especially since the methods read as instance methods (editor trick or not). An abstract class is heavy weaponry, every implementor must now inherit the abstract class and since you can only inherit once this puts a serious limitation on implementors. If you can't inherit you don't get the functionality. You could create a wrapper, but that's just a lot of boilerplate code. Besides, inheritance is added complexity/spaghetti too!
public interface ISomething
{
IEnumerable Stuff { get; }
}public static class SomethingExtensions
{
public static bool HasStuff(this ISomething something)
{
return something.Stuff.Any();
}
}How is this not awesome? Every implementor now getsHasStuff
for free without the need for inheritance!You agree that extension methods are clean for LINQ and when dealing with third party code, but for your own code it's suddenly spaghetti? Sounds like double standards to me ;)
Read my (free) ebook Object-Oriented Programming in C# Succinctly.
Visit my blog at Sander's bits - Writing the code you need.
Or read my articles here on CodeProject.Simplicity is prerequisite for reliability.
ā Edsger W. DijkstraRegards,
Sander -
just curious. recently I start to use extension methods in my projects.
diligent hands rule....
Yes, quite a bit. I love the extension method concept. Now if they could just implement "extension properties". Yes, I know you can use extension methods to pseudo-implement properties, but a full-blown extension property implementation would be sweet...
-
I mostly use them for things that can't have methods defined on them directly, interfaces and enums.
For some reason I never thought of writing them for enums, though I use them for interfaces all the time. Can you give an example where an extension method for an enum would be useful? Can't think of any myself off hand.
-
Why not implement in the object themselves and keep them contained and organized? Is there anything preventing the code to be where it belongs?
To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia
Separation of concerns, mostly.
cheers Chris Maunder
-
just curious. recently I start to use extension methods in my projects.
diligent hands rule....
The core products for the company I work for are mainly COM based libraries. I've written .Net libraries of extension methods that help hide the COM ugliness and provide a more .Net friendly interface.
-
just curious. recently I start to use extension methods in my projects.
diligent hands rule....
I have a .NET Core based Redis Client that I've been working on for a while that heavily uses extension methods. The 'client' just knows how to send a command and receive a response. All the Redis commands are implemented as extension methods on the 'client'. So as static class for the Key Commands, another for the Hash Commands, ... in Redis Client
/// <summary>
/// Sends a command and returns the response string.
/// </summary>
/// <param name="command">The Command.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>The response.</returns>
public Task SendAsync(string command, params object[] parameters)
{
return SendAsync(command, (IEnumerable<object>)parameters);
}/// <summary>
/// Sends a command and returns the response string.
/// </summary>
/// <param name="command">The Command.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>The awaitable Task.</returns>
public async Task SendAsync(string command, IEnumerable<object> parameters = null)
{
await EnsureConnected().ConfigureAwait(false);
await _commandWriter.WriteRedisCommandAsync(command, parameters).ConfigureAwait(false);
}in HashCommands
public static Task SendHGetAsync(this RedisClient client, string key, string field)
{
if (string.IsNullOrWhiteSpace(key))
throw new ArgumentNullException(nameof(key));if (string.IsNullOrWhiteSpace(field)) throw new ArgumentNullException(nameof(field)); return client.SendAsync("HGet", key, field);
}
Each commands are small and trivial. The core client has no tricky dependencies on the commands. Classic Open for Extension but Closed for Modification. What has been delaying me is the number of tests to test all the commands, plus an update to the latest .NET Core bits. Another great thing about Extension Methods is the ability to extend 3rd party libraries.
"Time flies like an arrow. Fruit flies like a banana."
-
For some reason I never thought of writing them for enums, though I use them for interfaces all the time. Can you give an example where an extension method for an enum would be useful? Can't think of any myself off hand.
-
just curious. recently I start to use extension methods in my projects.
diligent hands rule....
I used them extensively.
-
Well it depends on what that enum is about, it's not always useful. I've used it for example to give an `enum ConditionCode { etc` the fake-methods `Invert` and `SwapOperands`.
Ah gotcha. Thanks!
-
just curious. recently I start to use extension methods in my projects.
diligent hands rule....
What is extensively? I have a small set of extension methods, but I use them a lot. On sealed classes. Examples: DBInt("columnName") - returns int value of column in a datarow, and cleans up DBNull issues. HiddenCreditCard(CC Number String) - returns CC Number showing only first and last four digits, with asters in between.
-
Very much so! Done properly, they make the code so much more compact and readable.
Cheers, Mick ------------------------------------------------ It doesn't matter how often or hard you fall on your arse, eventually you'll roll over and land on your feet.
Not only does proper use of extension methods do this it also "cleans" up the API. For instance, Visual Basic has a StrReverse(string) method, but the underlying dotNet framework's Reverse() extension method for System.String doesn't return a string. It returns an array of characters. I'll add extension methods for this type of situation.
-
just curious. recently I start to use extension methods in my projects.
diligent hands rule....
I use extension methods somewhat. I'm slowly building a suite of useful methods. There is also the site extensionmethod.net too. I keep the extension methods in a core library, but the methods are declared in the namespace of the class I'm targeting. That way, when I reference the core library all the extension methods are available without superfluous using statements. Be careful, there is an ongoing debate on the internets about whether they're a good thing or bad thing. I would say, use sparingly, and note that an extension method is probably sign-posting a limitation in your design. As well as other suggestions, I've used them to clean up a messy code base I've inherited. In this code base there were a number of inappropriate methods attached to a static globals class. Side-stepping the whole issue of a statics globals class, the methods attached to it were moved onto extension methods. Not a perfect solution, but migrating to extension methods helped me nudge the legacy code in the right direction.