Should extension methods have a prefix? - c#

From what I have read about extension methods, you will run into problems if the base class decides to add a method with the same name as your extension. For a specific class it is generally not to hard to pick a name to avoid clashes, however extension methods can be added to interfaces which adds infinitely more potential for conflicts.
In Objective-C (with their version, categories), this problem is avoided by adding a prefix before each method. I know we can define extension methods in namespaces so that we can control whether they are imported or not, but this only solves the problem of clashes between extension methods, rather than clashes between an extension method and the base class.
Update:
Nobody, actually mentioned this, but extension methods aren't virtual. That means if you can i.myExtension() on an interface i, then it will always call the interface classes method, so the subclass method (which could have different intent) won't be called. So, overall, using extension methods is quite safe.

The use of a prefix will make the code ugly, which removes some of the value of an extension method.
I recommend instead, being careful to not create a large number of extension methods and to use method names that make sense. This way, in the case of a conflict, it's more likely that, for instance, the extension Where method and the conflicting Where method will have similar semantics.

The common convention is to have them in their own separate namespace (usually in the form of <something>.Extensions) which you can then use to decide whether or not you use them in any particular piece of code which contains types the extensions normally operate on.
Furthermore, if you do have a conflict, remember that extension methods are still static methods, so you can always call them explicitly in the case of a name conflict.
However, if you find that you are frequently running into name conflicts, you might want to reconsider the names you are choosing so that they don't interfere with names that already exist on the type.
To summarize, no, you should not prefix extension method names in C#, as they only serve to obfuscate your code and make it harder to maintain.

If the base class implements a method with the same name as your extension, I'd guess you'd have one of these two scenarios:
The base class implemented the same functionality you were adding yourself with an extension method. You no longer need the extension method. Delete it and use the method on the base class instead.
The base class implemented something different from what you wanted but gave it the same name. Either you or they are using the wrong name. Probably you. Rename your extension method to something that describes what the function actually does.

I'm inclined to say no they shouldn't unless you have reason good to suspect that the method signature you are using is going to be implemented. The reason i think this is...
It's is quite unlikely that your method signature will be duplicated in most cases.
If it does, it should always be detected in unit tests.
Should be trivial to fix.
I normally opt for relatively verbose method names when implementing extension methods anyway to avoid confusion.

Related

How can I prevent methods from being added to a class?

I'm trying to find out if there's a way to stop functions/methods from being added (EDIT: by other developers) to a class for the case where the object is a Model or DTO which should not contain methods (to prevent 'abuse' of the Models/DTOs by others, who may try and add 'helper' methods etc).
Is there any way to achieve this?
Use reflection and write a unit test that fails if a model-class has methods.
Mark all you model classes with a custom attribute. Then make a unit test that uses reflection to load a given assembly, iterate all classes in that assembly and check that classes marked with the model attribute does not have methods. This should be fairly straight forward using reflection.
I believe you are trying to solve a procedural issue with code where you should be using communication.
Your colleagues (i assume) are operating on the code files with 'full trust' privileges. If they break that privilege you should open a dialogue. Use the change as an opportunity to educate them on the intended design. Perhaps they are correct and you will be educated!
I suggest simply making the intended design obvious in the class name and with a comment stating the intended nature. Perhaps quote the design document(s) that informed the class.
You cannot hinder anyone with full write-access to your code-base to do so. The only two things you may do to avoid it are create some CodeAnalysis-rule for FXCop as mentioned by Christian.K in the comments or by writing your DTO-class so that it is undoubtly a DTO that should not have any methods by using a unambigious name for the class and if this is not enough provide some code-comments that notifies the coder to do not so.
However you may need some kind of method if using collections e.g. where you will need some kind of comparision if two instances of your DTO are equal, so you have to provide at least an Equals- and GetHashCode-method.
You don't need to use a struct to prevent additions to a class. You can use the sealed keyword
public sealed class MyDTOObject { ... }
Now, you can not inherent a class and also prevent inheritance (which is essentially what you're asking). The very fact of inheriting MyDTOObject is creating a new class which is based off of not equal to, or restricted, or defined in any way by the implementation of MyDTOObject.
You can use an abstract class, to force derived classes to implement certain methods, but not the other way around.
If you want to prevent others from deriving from your class and implementing helper methods, you must use the sealed keyword, or mark the class internal.
You may prevent the class being extended or inherited by marking it final that way nobody would be able to extend your class and hence not being able to add any behavior. But stop and ask yourself whether you want to do that or not, because then you'd be signing an invisible contract that everything ever required by the class is written in the class and this class needs no further addition.
To be clear, I was talking in Java context.

Extension Method vs. Helper Class [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Extension Methods vs Static Utility Class
I am building an API of general functions which perform actions based upon objects in .NET. For example; I have created a function that checks a string to see if it is an email address.
I could either have:
static bool IsEmailAddress(string text)
{
return IsMail(text);
}
or I could create an extension method that would be used like so:
string text = "HelloWorld#Email.com";
if (text.IsEmailAddress())
{
}
which is more suitable, or do you think since this is a general purpose library, I could technically implement it both ways and allow the developer to decide which is best for them?
Creating an extension method means that it will automatically show up during intellisense when a user uses that type. You have to be carefull not adding a lot of noise to the list of methods developers browse (especially when creating a reusable framework). For instance, when those methods are just usable in a certain context, you are probably better of using 'normal' static methods. Especially when implementing extension methods for general types such as string.
Take for instance an ToXml(this string) extension method, or an ToInt(this string) extension methods. Although it seems pretty convenient to have these extension methods, converting text to XML is not something you will do throughout the application and it would be as easy to have do XmlHelper.ToXml(someString).
There is only one thing worse, and that is adding an extension method on object.
If you're writing an reusable framework, the book Framework-Design-Guidelines by Krzysztof Cwalina is an absolute must read.
I prefer Extension Method, because your code is elegant, and you can define an extension method on a sealed class of the framework.
The question is which .NET Framework will you target? If < 3.5 then extension methods are not available. Otherwise, why would you create a new class?
An extension method is automatically part of a static class. This means that the consumer can use either the extension methods or call the static method from the class if she wants it. I use extension methods as much as I can, they are easier to discover if they're put in the proper namespace.
Extension methods allow developers to not be aware exactly what the helper class is called and where it is located, not to mention the very fact of its existence. Do note, that you still need to put their namespace in using clause - perhaps place them in some common, top-level namespace for your application.

Should extension methods only be used on classes whose code you don't have access to?

Should extension methods only be used on classes whose code you don't have access to?
I'm struggling to come up with a reason to have extension methods versus making it partial and adding the classes in an external file.
My specific scenario is as follows: I have classes that represent entities in a database via EF. I'm debating making the classes it renders partial and adding my own methods. Are extension methods a more valid alternative approach or are they not intended to be used when you have access to the code of the class you are extending?
The canonical counter-example is extension methods on an interface, as even if you control the source, there is no implementation. See: Linq.
But, yes, generally speaking, if you control the source of the concrete class, it is not unreasonable to expect to add the functionality to the class directly rather than using an extension method, if it makes sense for the functionality to actually be part of the class instance.
On the other hand, and coming back to your situation, you might consider neither approach. Your entities are data models, I would not add methods to those models, but rather encapsulate that functionality elsewhere. Those models exist to encapsulate your data, logic that might operate with or against that data might be better served in a different unit. But that really depends upon what your methods are doing, and also assuming they're not something like a trivial wrapper over one or more properties, for example.
Apart from the ability to provide extensions to interfaces, I use extension methods to add 'members' to a class that work using only the class' public interface. So if a method needs access to a private/protected member, it will become a class member, if not an extension method. This keeps the classes themselves small and focused...
No.
You may have a class that works fine in ninety percent of your projects. By adding an extension method you don't 'pollute' the original class but can still leverage it in the other ten percent of your projects.
Should extension methods only be used on classes whose code you don't have a access to?
Not necessarily. There are situations where extension methods can still help. I recently had an issue with the xml serializer where it could serialize an object that had a method that made use of a linq / lamba expression. Moving the method to an extension method resolved that. I like to use extension methods on DTOs also.
You might want to look at How Non-Member Functions Improve Encapsulation. There are some C++ specifics, but main idea applies to other OO languages as well. In short: the less methods you have in a class the easier it is to understand who and how changes private class state.

Extension Methods forward compatible

With extension methods we can easily add methods to any type. Obviously this opens the possibility in a future version of .net the extension method could no longer get called (for example the type now includes a method with identical signature to the extension method).
Should this be a concern?
If so, how should I deal with this and design my extension methods as to minimise code changes should this happen?
If the framework is changed so much in the future, there will always be compatibility issues. If a new framework method is added with the same name as your extension method, it is quite likely that they have the same, or at least very similar functionality and a refactoring is due anyways.
I think that the power of the extension methods is too large to ignore just because of this risk.
I'm afraid that the only thing you can do is providing unique enough names to your extension methods so you're 100% sure you will never have a conflict.
Not talking about adding the name of your cat to the method's name, just try to be more creative :)
Use obscure method names that would never be used in the framework.
edit -- perhaps obscure wasn't the most appropriate word, please substitute with meaningful but less common verbage
Attempting to avoid signature conflicts is really the only strategy to avoiding the hassle of code rework (assuming the functionality of the extension method needs to be preserved and not simply converted to the framework's definition of the method).

Recommendations for naming C# classes/methods intended to replace existing APIs

Long explanation aside, I have a situation where I need to basically re-implement a .NET framework class in order to extend the behavior in a manner that is not compatible with an inheritance or composition/delegation strategy. The question is not a matter of whether the course of action I am to take is what you would do, or recommend, it is instead a question of naming/coding-style.
Is there a paradigm for naming classes and methods that have the same functionality as an existing class or method ala the convention of ClassEx/MethodEx that exists in C++?
[edit]
I understand that choosing good names for this is important... I haven't written a line of code yet, and am instead taking the time to think through the ramifications of what I am about to undertake, and that includes searching for a clear, descriptive, name while trying to be concise. The issue is that the name I have in mind is not terribly concise.
[/edit]
Here are the ways I've seen in the .NET Framework itself:
Call it something slightly different, but don't use any specific suffix. For example, System.TimeZoneInfo was introduced to supersede System.TimeZone.
Put it in another namespace. For example, the WPF Button is in System.Windows instead of System.Windows.Forms.
Suffix it with a number. For example X509Certificate2 versus X509Certificate. (This practice was common with COM interfaces but has fallen out of favor in .NET.)
Note that the naming of TimeZoneInfo is a publicized case of Microsoft tackling this convtrovertial naming issue head on. See and http://blogs.msdn.com/kathykam/archive/2007/03/28/bye-bye-system-timezone2-hello-system-timezoneinfo.aspx and http://blogs.msdn.com/kcwalina/archive/2006/10/06/TimeZone2Naming.aspx for excellent information.
Try name your classes/methods with real meaning.
For example, if you extending the Random functionality to create random strings, name the class StringRandom or StringRandomizer and such.
If you writing class with general purpose extension methods that applying to specific class/interface, for example IList, name it ListExtensions.
If you writing random.Next method that returns random number between minValue and maxValue including maxValue, name the method NextIncludingMaxValue.
If you writing queue.Dequeue method that is thread safe, name if DequeueThreadSafe.
If you writing queue.Dequeue method that blocking until other thread enqueueing an item, name it DequeueBlocking.
And such...
C#, for the most part, avoids these situations entirely due to the ease in which you can extend a class with new methods without breaking binary compatibility (you can add methods, at will, to a class, just not an interface), and through the use of Extension methods.
There are few reasons to ever do this in C#, unlike C++. In C++, adding a method breaks compatibility, so "Ex" becomes a much more common scenario.
I give all my methods (and properties) camelCase names: so for example Invalidate is a framework method name, and invalidate is the name of one of my methods.
This (using camelCase names) is unconventional, so some people object to it, but I find it convenient.
No such problem with class names (for which I use the conventional UpperCase), because for class names there are their namespaces to distinguish them from the framework classes.

Categories

Resources