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....
Related
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.
Books usually say that if the classes get too big to manage, rethink the implementation because it is quite possible that the design needs correction since classes have not been defined properly.
But in situations where classes are indeed big, for example when a class is being extended to implement the functionality of a control (Canvas for example), and there are many different things like hit-testing, drawing, managing the drawn items etc. Is it a good solution to use partial classes in such cases to separate 'different' things of a bigger container (such as a custom control)?
Secondly, as a more general and broader solution, what should be considered before moving to Partial classes?
It's an illusion. It's just separating the class into two physical files. You still run afoul of the Single Responsibility Principle, low cohesion, etc.
Partial classes are primarily intended for use with automated code generation tools. You can edit the partial class without worrying about it being overwritten when the other portion is regenerated by the tool.
Composition is one of several ways to avoid large classes. Class A has an instance of class B, and delegates to it for part of its functionality. In many cases dependency injection can be used to decouple the two classes (class A is passed an interface that class B implements, usually in A's constructor).
Yes, if the class is naturally large, using partial classes can help you manage the source code. I've used this before now to split the tests for a single production file into several source test files. Likewise when reimplementing LINQ to Objects, I used partial classes to put each LINQ "operator" in its own file - even though they all contributed to a class called Enumerable.
Partial classes aren't a good alternative to good design though - when you can make your actual classes smaller, it's worth doing so. If you find you've got a bit class which you want to break up, partial classes can help you to refactor the big class into two smaller classes - you can divide the class into two sections without changing the functionality at all, then perform the real split in a smaller step.
Hit testing seems not to be a task for a canvas and can easily be delegated to another class implementing an interface like
public interface IHitTester
{
List<Shape> GetHits(List<Shape> allShapes, Point point);
}
It enhances testability, allows you to experiment with different hit testing implementations (strategy pattern) and enhances the readability of your code.
I am sure that you can extract other tasks to other classes in the same way, if you rethink your canvas class.
I think the use of these outside of code generation is a total anti-pattern.
They are more or less equivalent to Regions which again were for code generation. I see some developers using them for aesthetic reasons and calling their use refactoring! When you try to find the definition of a class and are presented with serveral partial classes to chose from it's not very helpful. I think developers should use split window to open the same file twice instead of shuffling parts of the class into different files.
I am increasingly aware that my code in any single file can often span hundreds of lines quite easily and although I know the implementation might be sound, it still feels messy and unorganised.
I understand that there are situations where a lot of code is neccessary, but whats the best way to organise it all?
I've thought about separating variables from methods, privates from publics and internals but I don't want to because I can't help thinking that the components of ONE class belong in ONE file.
This whole thing is compounded when I'm working with the codebehind of a WPF window, which always seem to grow at an exponential rate into one huge mess very quickly.
Also: C# has a keyword called partial, which allows you to split a class over any number of files without affecting the functionality. However, I have noticed that Microsoft only seem to use partial to hide generated code from you (Winforms / WPF.) Which leads me to question whether splitting a class simply because it has many lines is a legitimate use of partial - is it?
Thanks
Separate your code into responsibilities. For each responsibility, define a single type. That is, follow the Single Responsibility Principal. Doing so will result in smaller units of code, each of which performs a very specific function. Not only does this result in smaller files, but also in better design and maintainability.
If your files are big because they contain a single class/struct that is big, then this is usually (but not always) a hint that your class is dealing with multiple concerns and can be refactored into a number of smaller, more specialised classes.
If I understand you, your main problem is that your forms end up being too big, which leads to the classes for those forms containing too much code, which is quite normal if your forms aren't very simple. The way to try minimize this is by using User Controls since if you move the controls to other classes, you also move the code behind to other classes.
It can sometimes make it a little more difficult to communicate between the controls, but that's usually more than made up for by the fact that the code in each class will be much easier to understand.
I tend to group properties, constructors, methods, and helper methods (private methods) together with regions. If I have a lot of methods, I create more regions based on what they do (especially good for overloads). And speaking of overloads, try minimizing your code with optional parameters.
As far as I understand partial means that the class exists in two separate files. Webforms and controls are partial because the other "part" of the file is the as[p|c]x file that goes with it.
I go on the theory that if you cant see an entire method on one screen (i.e. you have to scroll), you should break the method up into further methods - either in the same class or when the code will get used more than once into a helper class.
We use stylecop. It helps a bit because it enforces a structure on your code and an order for what should appear where. Hence you can then find your way around larger files a bit more intuitively.
To improve code readability: you can use the region block: https://msdn.microsoft.com/en-us/library/9a1ybwek.aspx . As for improving the structure and design of your code - consult some specialist books.
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.
I have been using the partial class modifier for some time in order to put helper classes in their own file.
Today we got a new guy and he said that the last team he worked with didn't allow partial classes for this because modifying a helper class that is in a separate file would cause the main partial class file to get out of whack with the changes. Also, they were only allowed to put a helper classes inside of the main class as the last resort so that everything remained decoupled.
What do you think? Is there any problem using partial classes like this or does it boil down to preference?
For instance, I usually have something like this:
MainClass.cs
MainClass.Helper1.cs
MainClass.Helper2.cs
...
// Inside of MainClass.cs I have code like this:
public abstract partial class MainClass
{
// ...
}
// Then in the MainClass.Helper1.cs I have:
partial class MainClass
{
private class Helper1
{
// ...
}
}
Partial classes are primarily for code-generator usage, such as designers - but I use the approach you have cited - in particular when an object implements multiple (non-trivial) interfaces, I find it useful to break it up 1 file per interface implementation. I also commonly have a file for the static methods, which are usually different enough from instance methods to warrant separation.
Personally I can't see anything wrong with using partial classes like this, but that's just my own opinion. The only thing that might seem like "bad practice" is to name your classes "Helper1" and "Helper2" (but that might be an example only for clarification).
If you're using partial classes like this, check out the (free) addin vsCommands (for Visual Studio 2008) that makes it really easy to group files in the solution explorer (just like designer files) without editing the project file.
Short answer:
If all of the classes are your code, you don't really need helper classes, which invalidates your need for partials.
Long answer:
I'm not sure that there is anything that says your practice is explicitly wrong. From my experience, if you've got several different files that compose the entire class, you do need a good reason to do so, because:
Partial classes reduce readability somewhat
If your classes have multiple helper classes within them, it may be a symptom of a poor design, I don't think I've ever run into a situation where I was forced to write helper classes for classes I created.
However, I think the best reason to use partial classes is code generation, where you want to be able to re-generate a file without losing custom work.
I'm not a very big fan of partial classes and don't use them myself.
The one time I do find them helpful and OK to use however is when you want to add something to the LINQ to SQL designer code, but apart from that I find if you are spreading the code out into different files just for the sake of it, it can make it very hard to read and manage.
Maybe if you have classes split into many files maybe your classes are doing to much... just a thought:)
I've actually done the same thing. As has been stated, there is a slight readability hit on deciphering the partial classes.
Decoupling is the main reason I like this solution. A private inner class is far less coupled to everything else, because nothing else can see it or use it (although they may be talking about the potential for it to access the parent class's private data, which would usually be a bad idea).
In my experience, there no difference between noramal class and partial class.If your design requires large stucture of class or implementing more interfaces then go for partial class. Any how both are same.
I think that if the nested classes are large enough that you feel the need to split them into their own files they should probably not be nested classes. Make them internal members of the same namespace as MainClass instead.
Partial classes really only exist to support code generators and using them to break programmer written code into manageable chunks is an indicator of poor design.
See this article for a hilarious example of what not to do with partial classes.
I usually never use partial classes for similar reasons stated above.
But! While not frequent I have sometimes found that extensively unit testing a class (usually external classes) leads to giant unit test classes. Splitting the unit test class into partial classes makes it a bit easier on the eyes and to understand.
Similar to the grouping idea when inheriting from multiple interfaces, unit test can be grouped for functions.
I think it's good to remember that your tool's default behavior is to create a low-level form of Coupling Not Cohesion; and view it skeptically, and override it unless it makes sense for some of the specific reasons listed above. But it's not good default behavior.
Most of times I use partial class only with code generation, so I can extend my classes' behaviors on separated classes that they need some customization and don't include in code generation.