Guidelines - extension methods vs partial class - c#

We are debating at work the best way to define methods for an entity class - as extensions methods or using partial classes. The kind of methods we're talking about don't modify the state of the entity, they are purely "helper" methods that interrogate the state and return a value.
The main benefit to both approaches is to keep the entity class clean, while still providing intellisense support to client code.
I don't have a strong preference either way but am curious to know if others have a preference (or know of documented guidelines) towards one or the other.
I started writing the list of merits for each approach that I could think of, but in the end all I've come up with is:
Partial Classes
The method definition resides within the class (even if it's another file) so Visual Studio tool support for "find method" (e.g. ALT-\ in resharper) will locate the method
The existence of the other file containing helper methods is obvious as soon as the entity class is opened due to use of the partial keyword
Extension Methods
The naming of the file ("entityNameExtension") and its whereabouts in the project (in an "Extensions" sub-folder) are intuitive and easy to search for
Can anyone else add their opinion to this?
PS I don't feel this is a duplicate of the following question, as the asker of that question was content to mark a response which outlined the functional differences as the correct answer, which doesn't answer the question about which approach is best practice in this scenario:
Partial Class vs Extension Method
EDIT - I'm seeking people's preference towards one approach or the other, as there are no documented guidelines that we can find for this particular scenario. Both approaches are possible and neither violates any design principles, so it is a matter of preference and I'd like to know yours.

In my opinion, extension methods are good for two things. First, when you apply them to interfaces, it gives you the illusion of writing an abstract base class that lets you define some common methods, but it's more flexible because a class can only have one base class but can implement multiple interfaces. Second, if you apply it to regular classes, then I tend to look at it as some kind of hacking. When the original class lacks some methods, and you really feel like they should have those methods, but they don't, and they are out of your reach, so you are forced to implement them somewhere else, as utility methods, and it gives you an illusion that it's actually there.
Both cases are syntactic sugar only in the end, but extending interfaces makes much more sense to me, if I just look at LINQ's Enumerable class for example. I've used those extension methods on dozens of completely different classes, so it really paid off. An example of a class extension method is when I made my own string.IsNullOrWhitespace before it was added to the framework.
Extending an interface seems right because the interface defines a contract, and you can rely on that contract in your extension method, but when you extend a regular class, it may change and break your extension method. Of course, interfaces may change, too, but they tend to be more thoroughly designed I think, but I don't have any statistics.
Then there's the case of object-oriented programming. Where do you feel like your method should go, who uses those additional methods, where are the boundaries. If you think a method belongs inside a class, then put it in the class. It makes sense, it's simple. People wrote really good classes before extension methods were invented, they put everything where it belonged and life was good, haha.
Partial classes are cool because they are not that big of a hack as extension methods. They are not syntactic sugar, not magic. It is merely the best and easiest way to deal with auto-generated classes, so I don't think too much of it. I've written some code generators, and they emit regions where humans can write their own stuff and it is not overwritten in subsequent code generations. It is more comfortable that way, but that's all. I can't change how .NET tools generate code, and they don't do it this way, so partial classes are the next best thing.
To sum it up, my opinion is to only use extension methods when you really have to, and go with partial classes whenever possible.

I dont know why you would create a partial class uless your original class has grown out of its purpose. Take a look at your classes you would like to extend, are they really doing one thing, or are they doing many things. Take a look at at the Single Responsibility Principle (http://en.wikipedia.org/wiki/Single_responsibility_principle).
If you can create methods that OTHER CLASSES can take advantage of, I would recommend creating an extension class. It will extend the capability of other classes, making your toolbox more flexible.

Related

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.

Implementing interfaces in partial classes

Consider a class which implements a lot of interfaces, would it make sense to implement each interface in a separate file using partial class definitions?
Would this be an abuse of the language feature or is it an idiom I'm unaware of?
If your class has to implement many interfaces, that's a reasonable way of managing the source, yes. You can edit the project file to make several of them depend on one "main" class file, which makes the Solution Explorer easier to work with.
You should ask yourself whether you shouldn't have several smaller classes each implementing a single interface though. Sometimes that will be a better approach, sometimes not - but it's always worth asking the question.
Not an idiom I have ever heard of, but sounds like an elegant way to partition your code.
I think that you should ask yourself if having a .cs file for each interface implemented by your class would make it easier or harder to understand the code. How would you name the files?
Although I might be going out on a limb here I think I'm going to suggest that you use the much hated #region directive instead if organizing the code is your goal.
You can, yes, but that won't give you any more advantages over, say, a single file with regions. Partial classes tend to be icky because it's not immediately obvious that there is another part to it, and someone else looking at the class might miss it. I personally prefer to have everything in one place.
The only benefit is to have the various interface implementations in separate physical files.
In my opinion, this is outweighed by the downside of having your class declaration located in separate physical files.
Pro: can easily pinpoint what part of a class that implement which interface (good when you are using tool that doesn't allow navigating easily through code inside the IDE).
Con: easier to lose context since now you have to navigate across multiple files
I supposed w/ the advance in IDE nowadays, it doesn't really matter. You can have a single file and let the tool help you navigate inside your class structure quickly. But then again tool can help either way... so...
Partial is still good for separating generated code vs custom code.
It makes about as much sense as having constructors in one partial class file, properties in another partial class file, etc., etc.
i.e. Don't do it unless you have a good reason.
I think there are better ways of structuring your code than using partials in this case. There's no reference in Visual Studio that you can consult to see how many partial implementations there are for a particular class so it is easy to lose track.
Depending on how much interfaces you really mean with "a lot of interfaces" you can use regions to separate the implementations. That would be fine up until 10-15 interfaces with a total of, say, 150 functions to implement. After that, things will get messy and you will lose overview.
And that's where you will benefit from other mechanisms such as inheritance, encapsulation or aggregation, and the use of services and helper classes.
But I would seriously reconsider the architecture of your code if you ever come across the need to implement 15+ interfaces....

Are extension methods an object-oriented feature of C#?

Do extension methods follow the object-oriented paradigm in C#?
Is it a good practice to use extension methods?
In the software development lifecycle how should we consider this question in the design phase?
Eric Lippert has blogged about this and I suspect I can't do much better than to quote him:
So, yes, the oft-heard criticism that
"extension methods are not
object-oriented" is entirely correct,
but also rather irrelevant. Extension
methods certainly are not
object-oriented. They put the code
that manipulates the data far away
from the code that declares the data,
they cannot break encapsulation and
talk to the private state of the
objects they appear to be methods on,
they do not play well with
inheritance, and so on. They're
procedural programming in a convenient
object-oriented dress.
They're also incredibly convenient and
make LINQ possible, which is why we
added them. The fact that they do not
conform to some philosophical ideal of
what makes an object-oriented language
was not really much of a factor in
that decision.
I would add, however, that they're useful beyond just LINQ - for the same reason that they're useful in LINQ. It's really nice to be able to express algorithms which work on arbitrary implementations of a particular interface (such as IEnumerable<T> in LINQ to Obhects). Such algorithms typically don't have any context beyond the interfaces you're working on, so they're often naturally static.
If you accept that you've got some static utility method, which syntax would you rather use?
// Traditional
CollectionUtils.Sort(collection);
// Extension methods
collection.Sort();
The latter is simply more readable in my opinion. It concisely expresses what you want to do. It doesn't make it clear how you want to do it, but that's less important for most of the time - and more important when you're debugging that particular line, of course.
Extension methods are not an object oriented language feature. (compared to: classes, inheritance, polymorphism etc).
Like every language feature, it should be used where it is appropriate and for what it is designed for. There are already dozens of questions about when and how to use Extension methods.
What are the best practices for using Extension Methods in .Net?
Possible overuses of Extension Methods
Do Extension Methods Hide Dependencies?
There are two parts to it.
Is it OO when we use it
No; it makes you feel that you are calling method on the particular type
Is it OO based on how it is compiled/built
Yes; Compiled code has a static method using the object on which extension method was invoked
Extension methods are just a language feature. They work on object instances and are very nice tool.
Consider them as a different way to extend class functionality. You can add new functionality to a class:
By adding a partial class declaration. The class then instantly gets a bunch of new methods and properties.
By including a namespace with your extension methods holder class. The class then gets a bunch of new methods again.
Rather an organizational / language feature. Does not break object-oriented concept in any way. Just as header/source file division in C/C++ has nothing to do with object-orientation, just a language/framework feature.
It depends. Extension methods are just a tool. They can be very useful when used appropriately. But if you use them too much, it can obscure your code.
Extension Methods are just static methods that work with a specific Class or Class Hierarchy. Python is OO but has modules, Ruby has mixins. I see it more as a language feature. I am pretty sure its still OO friendly

evaluating cost/benefits of using extension methods in C# => 3.0 [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
In what circumstances (usage scenarios) would you choose to write an extension rather than sub-classing an object ?
< full disclosure : I am not an MS employee; I do not know Mitsu Furota personally; I do know the author of the open-source Componax library mentioned here, but I have no business dealings with him whatsoever; I am not creating, or planning to create any commercial product using extensions : in sum : this post is from pure intellectal curiousity related to my trying to (continually) become aware of "best practices" >
I find the idea of extension methods "cool," and obviously you can do "far-out" things with them as in the many examples you can in Mitsu Furota's (MS) blog postslink text.
A personal friend wrote the open-source Componax librarylink text, and there's some remarkable facilities in there; but he is in complete command of his small company with total control over code guidelines, and every line of code "passes through his hands."
While this is speculation on my part : I think/guess other issues might come into play in a medium-to-large software team situation re use of Extensions.
Looking at MS's guidelines at link text, you find :
In general, you will probably be
calling extension methods far more
often than implementing your own. ...
In general, we recommend that you
implement extension methods sparingly
and only when you have to. Whenever
possible, client code that must extend
an existing type should do so by
creating a new type derived from the
existing type. For more information,
see Inheritance (C# Programming
Guide). ... When the compiler
encounters a method invocation, it
first looks for a match in the type's
instance methods. If no match is
found, it will search for any
extension methods that are defined for
the type, and bind to the first
extension method that it finds.
And at Ms's link text :
Extension methods present no specific
security vulnerabilities. They can
never be used to impersonate existing
methods on a type, because all name
collisions are resolved in favor of
the instance or static method defined
by the type itself. Extension methods
cannot access any private data in the
extended class.
Factors that seem obvious to me would include :
I assume you would not write an extension unless you expected it be used very generally and very frequently. On the other hand : couldn't you say the same thing about sub-classing ?
Knowing we can compile them into a seperate dll, and add the compiled dll, and reference it, and then use the extensions : is "cool," but does that "balance out" the cost inherent in the compiler first having to check to see if instance methods are defined as described above. Or the cost, in case of a "name clash," of using the Static invocation methods to make sure your extension is invoked rather than the instance definition ?
How frequent use of Extensions would affect run-time performance or memory use : I have no idea.
So, I'd appreciate your thoughts, or knowing about how/when you do, or don't do, use Extensions, compared to sub-classing.
thanks, Bill
My greatest usage for them is to extend closed-off 3rd party APIs.
Most of the time, when a software developer is offering an API on Windows these days, they are leaning more and more toward .NET for that extensibility. I like to do this because I prefer to depend on my own methods that I can modify in the future and serve as a global entry point to their API, in the case that they change it.
Previously, when having to do this, and I couldn't inherit the API object because it was sealed or something, I would rely on the Adapter pattern to make my own classes that wrapped up their objects. This is a functional, but rather inelegant solution. Extension methods give you a beautiful way to add more functionality to something that you don't control.
Many other peoples' greatest usage for them is LINQ!
LINQ would not be possible without the extension methods provided to IEnumerable.
The reason why people love them is because they make code more readable.
I have noticed another MAJOR usage of extension methods (myself included) is to make code more readable, and make it appear as if the code to do something belongs where it is supposed to. It also gets rid of the dreaded "Util" static-god-class that I have seen many times over. What looks better... Util.DecimalToFraction(decimal value); or value.ToFraction();? If you're like me, the latter.
Finally, there are those who deem the "static method" as EVIL!
Many 'good programmers' will tell you that you should try to avoid static methods, especially those who use extensive unit testing. Static methods are difficult to test in some cases, but they are not evil if used properly. While extension methods ARE static... they don't look or act like it. This allows you to get those static methods out of your classes, and onto the objects that they really should be attached to.
Regarding performance..
Extension methods are no different than calling a static method, passing the object being extended as a parameter... because that is what the compiler turns it into. The great thing about that is that your code looks clean, it does what you want, and the compiler handles the dirty work for you.
I use extension methods as a way to improve the functionality for classes without increasing the complexity of the class. You can keep your classes simple, and then add your repetitive work later on as an extension.
The Min() and Max() extension methods are great examples of this. You could just as easily declare a private method that would calculate these, but an extension method provides better readability, makes the functionality available to your entire project, and didn't require making an array any more complex of an object.
Taking the sub-classing approach vs. extension methods requires a couple of things to be true
The type must be extendable (not-sealed)
All places the type is created must support a factory pattern of sorts or the other code will just create the base type.
Adding an extension method requires really nothing other than using a C# 3.0+ compiler.
But most importantly, an inheritance hierarchy should represent an is-a relationship. I don't feel that adding 1 or 2 new methods / behaviors to a class truly expressing this type of relationship. It is instead augmenting existing behavior. A wrapper class or extension method much better fits the scenario.
In some cases you can't use a subclass: string for instance is sealed. You can however still add extension methods.

Creating a Catch-All AppToolbox Class - Is this a Bad Practice?

Never sure where to place functions like:
String PrettyPhone( String phoneNumber ) // return formatted (999) 999-9999
String EscapeInput( String inputString ) // gets rid of SQL-escapes like '
I create a Toolbox class for each application that serves as a repository for functions that don't neatly fit into another class. I've read that such classes are bad programming practice, specifically bad Object Oriented Design. However, said references seem more the opinion of individual designers and developers more than an over-arching consensus. So my question is, Is a catch-all Toolbox a poor design pattern? If so, why, and what alternative is there?
Great question. I always find that any sufficiently complex project require "utility" classes. I think this is simply because the nature of object-oriented programming forces us to place things in a neatly structured hierarchical taxonomy, when this isn't always feasible or appropriate (e.g. try creating an object model for mammals, and then squeeze the platypus in). This is the problem which motivates work into aspect oriented programming (c.f. cross cutting concern). Often what goes into a utility class are things that are cross-cutting concerns.
One alternative to using toolbox or utility classes, are to use extension methods to provide additional needed functionality to primitive types. However, the jury is still out on whether or not that constitutes good software design.
My final word on the subject is: go with it if you need, just make sure that you aren't short-cutting better designs. Of course, you can always refactor later on if you need to.
I think a static helper class is the first thing that comes to mind. It is so common that some even refer to it as part of the object-oriented design. However, the biggest problem with helper classes is that they tend to become a large dump. I think i saw this happen on a few of the larger projects i was involved in. You're working on a class and don't know where to stick this and that function so you put it in your helper class. At which point your helpers don't communicate well what they do. The name 'helper' or 'util' itself in the class name doesn't mean anything. I think nearly all OO gurus advocate against helpers since you can very easily replace them with more descriptive classes if you give it enough thought. I tend to agree with this approach as I believe that helpers violate the single responsibility principle. Honestly, take this with a grain of salt. I'm a little opinionated on OOP :)
In these examples I would be more inclined to extend String:
class PhoneNumber extends String
{
public override string ToString()
{
// return (999) 999-9999
}
}
If you write down all the places you need these functions you can figure out what actually uses it and then add it to the appropriate class. That can sometimes be difficult but still something you should aim for.
EDIT:
As pointed out below, you cannot override String in C#. The point I was trying to make is that this operation is made on a phone number so that is where the function belongs:
interface PhoneNumber
{
string Formatted();
}
If you have different formats you can interchange implementations of PhoneNumber without littering your code with if statements, e.g.,
Instead of:
if(country == Countries.UK) output = Toolbox.PhoneNumberUK(phoneNumber);
else ph = Toolbox.PhoneNumberUS(phoneNumber);
You can just use:
output = phoneNumber.Formatted();
There is nothing wrong with this. One thing is try to break it up into logical parts. By doing this you can keep your intellisense clean.
MyCore.Extensions.Formatting.People
MyCore.Extensions.Formatting.Xml
MyCore.Extensions.Formatting.Html
My experience has been that utility functions seldom occur in isolation. If you need a method for formatting telephone numbers, then you will also need one for validating phone numbers, and parsing phone numbers. Following the YAGNI principle, you certainly wouldn't want to write such things until they're actually needed, but I think it's helpful to just go ahead and separate such functionality into individual classes. The growth of those classes from single methods into minor subsystems will then happen naturally over time. I have found this to be the easiest way to keep the code organized, understandable, and maintainable over the long term.
When I create an application, I typically create a static class that contains static methods and properties that I can't figure out where to put anywhere else.
It's not an especially good design, but that's sort of the point: it gives me a place to localize a whole class of design decisions that I haven't thought out yet. Generally as the application grows and is refined through refactoring, it becomes clearer where these methods and properties actually ought to reside. Mercifully, the state of refactoring tools is such that those changes are usually not exceptionally painful to make.
I've tried doing it the other way, but the other way is basically implementing an object model before I know enough about my application to design the object model properly. If I do that, I spend a fair amount of time and energy coming up with a mediocre solution that I have to revisit and rebuild from the ground up at some point in the future. Well, okay, if I know I'm going to be refactoring this code, how about I skip the step of designing and building the unnecessarily complicated classes that don't really work?
For instance, I've built an application that is being used by multiple customers. I figured out pretty early on that I needed to have a way of separating out methods that need to work differently for different customers. I built a static utility method that I could call at any point in the program where I needed to call a customized method, and stuck it in my static class.
This worked fine for months. But there came a point at which it was just beginning to look ugly. And so I decided to refactor it out into its own class. And as I went through my code looking at all the places where this method was being called, it became extremely clear that all of the customized methods really needed to be members of an abstract class, the customers' assemblies needed to contain a single derived class that implements all of the abstract methods, and then the program just needed to get the name of the assembly and the namespace out of its configuration and create an instance of the custom features class at startup. It was really simple for me to find all of the methods that had to be customized, since all I needed to do was find every place that my load-a-custom-feature method was being called. It took me the better part of an afternoon to go through the entire codebase and rationalize this design, and the end result is really flexible and robust and solves the right problem.
The thing is, when I first implemented that method (actually it was three or four interrelated methods), I recognized that it wasn't the right answer. But I didn't know enough to decide what the right answer was. So I went with the simplest wrong answer until the right answer became clear.
I think the reason it's frowned upon is because the "toolbox" can grow and you will be loading a ton of resources every time you want to call a single function.
It's also more elegant to have the methods that apply to the objects in the actual class - just makes more sense.
That being said, I personally don't think it's a problem, but would avoid it simply for the reasons above.
I posted a comment, but thought I'd elaborate a bit more.
What I do is create a Common library with namespaces: [Organisation].[Product].Common as the root and a sub namespace Helpers.
A few people on here mention things like creating a class and shoving some stuff they don't know where else to put in there. Wrong. I'd say, even if you need one helper method, it is related to something, so create a properly named (IoHelper, StringHelper, etc.) static helper class and put it in the Helpers namespace. That way, you get some structure and you get some sort of separation of concerns.
In the root namespace, you can use instance utility classes that do require state (they exist!). And needless to say also use an appropriate class name, but don't suffix with Helper.

Categories

Resources