简体   繁体   中英

Usage of extension methods for framework types

In a new line of work I have been told to avoid using Extension Methods for Types that you (or your organization) have no control over, meaning external libraries, framework types such as string, list, and others.

The argument I was given is that this will be bad if the framework developer now decides to implement a method that has the same names and/or parameters as your extension method.

While this problem may arise, this argument effectively reduces the usability of extension methods to nearly zero. Would this argument be considered valid? I am not suggesting to use extension methods everywhere, but I would like to know of similar arguments for and against it.

It's an argument which has some merit, but in lots of cases the problems can be avoided:

  • If you control your code and can easily update it if necessary, then you can easily write unit tests to detect the problem and correct it if it occurs. (I assume you'd be validating any update to the external library before deploying it anyway.)
  • If you trust the external library developer to follow normal good practices for backward compatibility, then they shouldn't be adding members to interfaces anyway, as that would break existing implementations... so you could at least write extension methods for interfaces.
  • If your extension methods have names which would be very unlikely to be added to the external libraries, then practically speaking it's not an issue. For example, if your company writes Frobulators, and that's a term which is specific to you, then writing

     public static Frobulator ToFrobulator(this string Frobulator) 

    really isn't going to be a problem in reality.

Of course, the risk is there, but defining something on closed or sealed types you have no control over is exactly what extension methods is about. If you'd only create extension methods on types from your own, the effectiveness of extension methods (compared to regular methods) would be minimized.

There is a very easy 'solution' for this in naming conventions. If you'd prefix or postfix your extensions with a specific identifier, you will be sure Microsoft doesn't create a similar method.

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