Best Practices: When not/to use partial classes - c#

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.

Related

Using Partial Classes to manage code, good solution?

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.

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....

class definition and implementation in C# vs C++

With C++, I can have one class definition in a header file, and have a multiple implementation files by including the header file.
With C#, it seems that there is no such header file, as one class should contain both definition/implementation.
I wonder if the number of lines can be very big, because one can't separate the class into multiple files. Am I correct? I mean, in some cases, one can't change the class design to have smaller classes. In this case, is there a way to solve this problem?
You can separate a class into multiple files using the partial keyword
public partial class ClassNameHere
{
}
It is possible to split the definition of a class or a struct, or an interface over two or more source files using the Partial keyword modifier Link to msdn with the partial class
Partial classes only give you so much. There is still no way, that i know of, to split your class definition from implementation, such that each exists in a separate file. So if you like to develop based on a need-to-know paradigm then you are sort of stuck. Basically there are three levels a developer can work at...
1) Owns all the code and has access to, and maintains all of it.
2) Wishes to use some useful base class(s) which may form part of a framework, or may just be a useful class with some virtual methods, etc, and wishes to extend, or re-implement some virtual base class methods of interest. Now the developer should not need to go and look at the code in the base class(s) in order to understand things at a functional level. If you understand the job of a function, it's input and output parameters, there is no need to go and scratch inside source code. If you think there's a bug, or an optimization is needed, then refer to the developer from 1) who owns and maintains the base code. Of course there's nothing saying that 1) and 2) cannot be associated with the same developer, in which case we have no problem. In fact, this is more than often the case i suspect. Nevertheless, it is still good practice to keep things well separated according to the level at which you are working.
3) A developer needs to use an already packaged / sealed object / component dll, which exposes the relevant interfaces.
Within the context of c#, 1) and 3) have no problems. With 2) i believe there is no way to get round this (unless you change from exposing virtual base methods to exposing interface methods which can be reimplemented in a component owning the would-be base class). If i want to have a look at a class definition to browse over the methods, scaffolding functions, etc, i have to look at a whole lot of source code as well, which just gets in the way of what i am trying to focus on.
Of course if there is class definition documentation external to how we normally do it ( in headers and source files), then i must admit, that within the context of 2), there is not reason to ever look into a class definition file to gain functional knowledge.
So maybe clever Tom's came up with c#, decided to mix class definition with implementation in an attempt to encourage developers to have external documents for their class definitions, and interfaces, which in most IT companies is severely lacking.
Use a partial class as #sparks suggests, or, split into several classes. It's a good rule of thumb that, if you can't fit a class onto a couple of pages, it's complicated enough to need breaking apart.

Are C#'s partial classes bad design? [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 4 years ago.
Improve this question
I'm wondering why the 'partial class' concept even exists in C#/VB.NET. I'm working on an application and we are reading a (actually very good) book relavant to the development platform we are implementing at work. In the book, the author provides a large code base/wrapper around the platform API and explains how he developed it as he teaches different topics about the platform development.
Anyway, long story short - he uses partial classes, all over the place, as a way to fake multiple inheritance in C# (IMO). Why he didn't just split the classes up into multiple ones and use composition is beyond me. He will have 3 'partial class' files to make up his base class, each w/ 3-500 lines of code... And does this several times in his API.
Do you find this justifiable? If it were me, I'd have followed the S.R.P. and created multiple classes to handle different required behaviors, then created a base class that has instances of these classes as members (e.g. composition). Why did MS even put partial class into the framework? They removed the ability to expand/collapse all code at each scope level in C# (this was allowed in C++) because it was obviously just allowing bad habits - partial class is, IMO, the same thing. I guess my question is: Can you explain to me when there would be a legitimate reason ever to use a partial class?
EDIT: I'm aware that for Web/WinForms there is no other choice. But outside of this? Why didn't MS just put some different keyword for gluing code-genn'ed classes together? Or is there really a legit design scenario that merits it?
I do not mean this to be a rant / war thread. I'm honestly looking to learn something here. When should partial classes be used in code design? Simple question, no need to close
Thanks
Can you explain to me when there would be a legitimate reason to ever use a partial class?
One of the most legitimate and useful reasons is to encourage the separation of automatically generated code and your own custom extensions to it. For instance, it's common to have an automatically generated form code from some kind of designer, but you usually want to add your own specific behavior to it. This way, if you regenerate the automatic-code portion, you're not touching the part that has your specific extensions.
That said, it's quite possible to have too much of a good thing. Some tips:
Don't make your classes partial for the sake of being partial.
Don't put partial classes anywhere except besides one another. If you have to jump to a completely unrelated section of the project to see the other half of the class, you're probably doing it wrong.
Don't use partial as a technique to obscure the size of the class. If you're breaking up your classes with partial because they're too big, you should revisit the Single Responsibility Principle.
If you have three or more partial fragments for the same class, it's almost a guarantee that you're abusing partial. Two is the typical upper bound of reasonableness, and it's generally used to segment automatically-generated code from handwritten code.
Anyway, long story short - he uses partial classes, all over the place, as a way to fake multiple inheritance in C# (IMO). Why he didnt just split the classes up into multiple ones and use composition is beyond me. He will have 3 'partial class' files to make up his base class, each w/ 3-500 lines of code... And does this several times in his API.
Yes, that's definitely a clear abuse of partial!
There are two reasons that I would (and do) use partial classes.
To separate auto-generated portions of the code (such as WinForms designer code or T4 output).
To allow nested types their own file while still achieving the encapsulation required by your design.
Update
I can see that some are not convinced about my second point, so let me give an example; the ListViewItemCollection in the framework. It is quite rightly nested under ListView because it is only for use by ListView, but to make maintenance much easier, I would give it it's own file by using partial classes. I don't see this as bad design or a misuse of the partial keyword.
For more discussion, check out the question that this one duplicates: Partial Classes in C#
Another legitimate use of partial classes is to help reduce the "monolithic web service" clutter in WCF. You want to to break it down into logical groups of functionality but don't want to have to create a ream of individual service instances/endpoints (presumably because they share state, resources, and so on).
The solution? Have the service implement multiple interfaces, and implement each interface in its own partial class. Then map different endpoints in the configuration to the same physical implementation. It makes the project a lot more maintainable, but you still only have one physical endpoint.
In some cases I'd point to this type of approach as a poor practice on account of the SRP, but when you're working with WCF services or web services in general, it's not quite so simple. You have to balance internal design requirements against external consumption requirements.
One less common use might be to split up a huge class into separate physical files to make life easier from a source control point of view. I've just joined a project containing some enormously bloated web service classes running to thousands of lines of code and with methods related to several different business functions.
Merging from various feature branches is a nightmare due to different teams making simultaneous unrelated changes in the same file. I can't split the web service up without making some seriously breaking changes, but breaking the class up into partial classes preserves the behaviour exactly, and removes a whole bunch of merging issues.
I'm definitely not encouraging the above as a design choice, but it was a nice quick win for us, and goes to show that partials aren't evil all the time...
I've used partial classes in many different ways in the past. As I learn more about programming and in particular the concept of "favor composition over inheritance" I can easily see the need diminishing for both vertical inheritance and overuse of partial classes.
Other than auto-generated code, I cannot think of good use of partial classes. Even if you use EF, and need different metadata, they don't even recommend using partials for metadata. In fact if you try to duplicate any properties in another partial(just to add metadata) you'll get a compiler error.
The more we learn about refactoring and SOC (Separation of Concerns) the smaller and more focused our classes become. They are by default, re-used, which over time makes them bullet-proof and easily tested. Just say NO to gargantuan programs. Henry Ford learned this concept in the early 1900's programmers started learning it 100 years later.
Use composition when you can...
I fully agree with John's answer. But I would take it one step further.
Don't make your classes partial.
The only use of partial classes I can think of that I would consider "good design" is with automatically generated code. Any other use is almost certainly unnecessarily splitting up your class. (Actually, I can see that Jeff's second point on nested classes is possibly a valid use)
Personally I think this book you are reading sounds like bad design, however do consider that he may just be using partial classes so he can just demo part of the code little bits at a time rather than just presenting the whole class in one go.
Can you explain to me when there would be a legitimate reason to ever use a partial class?
Recent versions of Visual Studio use partial classes to seperate the auto-generated designer code from your own code..
An ASP.NET example:
Page.aspx
Page.aspx.cs <- Your code
Page.aspx.Designer.cs <- A partial class containing auto generated code.
A WinForms example:
Form1.resx
Form1.cs <- Your code
Form1.Designer.cs <- A partial class containing auto generated code
I've used partial classes to "physically" separate static data access methods from business class properties and methods in an active record architecture. For example, we had Company and CompanyData partial classes side-by-side. The advantage was that one file was the POCO and the other contained only data access methods. This was a stepping stone to removing data access to repository classes in a legacy application. I think that was a legitimate use, it certainly made the re-factoring process saner.
Another good use for partial classes would be when implementing the Abstract factory pattern. Make the root factory object partial and then place the actual factory methods in the same file as the class the factory instantiates.
EDIT: Partial classes also work well for classes that interact with a configuration file. Place the code containing the configuration parameters near the code that actually uses the configuration parameter.
Just stumbled across this thread while googling the benefits of partial class.
I am in the process of converting a Java EE application into a silverlight based .NET one.
I came across the following code in the view layer :
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
...
public partial class Wwcusts04d : System.Windows.Controls.Page {
Now, if the partial page itself is autogenerated, what's the use of maintaining it ?
Also, the code inside just links various controls to their names. I don't confess to have knowledge of silverlight, but isnt this thing better suited in xaml?
Partial class exists in the .Net framework solely to let Visual Studio designers (e.g. the Asp.Net designer and the Windows Forms designer) to generate code / mess with your classes while keeping that generated code in a separate file.
(See .NET Partial Classes vs. Inheritance)
If you do something similar (generate code that needs to coexist with user-written code) then you might also find partial classes useful, but I don't believe that Microsoft ever intended partial classes as a language concept to be useful to anyone other than the Visual Studio team.
Its not so much that using Partial classes is bad design - its just you probably wont find a use for them.
I've used a partial class twice in VB.Net, and both times were for the rare occasion that I needed late binding. Simply create a partial class and turn Option Strict Off at the top.
Just to add on to the previous answers that mentioned separating generated code from custom code, I've found partial classes useful for extending strongly-typed datasets.
There's a lot of discussion out there on this topic, and lots of people saying that 1) it's bad design to use partial classes, 2) that it's used for autogenerated code, and 3) that it shouldn't take the place of inheritance.
I have a situation, though, in which partial classes look like they'll come in very handy: I'm building a series of applications which will eventually be integrated into a suite. They'll all have a main form which will provide some functionality, and several shared components (e.g., a form to display reports). While I could define a base class and inherit from it, that would mean a lot of rework when the time comes to combine all of the applications into the "enterprise" version of the product.
Thus, partial classes are quite useful, because I can quite simply include the various partial classes into the combined version, while still allowing me to build the individual, stand-alone versions of the product. If I were to try to accomplish this using inheritance, I'd end up with each component calling its own version of the common components (e.g., InvoiceReportViewer, PurchasingReportsViewer, etc.) rather than simply calling ReportsViewer and knowing that Visual Studio will have integrated all of the bits for me.
Another thing to consider, partial classes forces you to create different file names which contains same class name. For example you have FactoryClass and you are creating partial versions of it like; Factory.designer.cs, Factory.data.cs and all those files has class named FactoryClass.
If you navigate to this question; there is a best practice defined as:
Best practice, however, is to define one class per file and to give the file the same name as the class (or struct, etc.) being defined.

Practical usage of partial keyword in C#

I know it lets visual studio to separate WinForms UI code from the UI events, etc. But are there any practical uses for it?
The partial keyword is typically used in code generation utilities to allow developers to add additional functionality to the generated code without the fear of that code being erased if the code is generated again.
With C# 3 the partial keyword can be applied to methods to allow users of generated code to fill in blanks left by the generator. The Linq To Sql designer for example provides partial methods that allow you to add logic to the classes that the framework will call if implemented. The benefit here is that the C# compiler will completely remove unimplemented partial methods, so there is no performance hit at all for not implementing them.
Partial classes can also be used to organize very large classes into separate code files, although this sort of usage is usually a sign that your classes are too large and are taking on too many responsibilities.
The best use for the partial keyword that I can think of is nested classes. Without the partial keyword all nested classes must go in the same code file as the containing class.
One use I have found is for code that you may not want to exist in production code such as tracing or dev logging code. You could place this in the partial class and then when you do a production build you simply build without those partials included and the compiler will auto-magically strip out any calls to those partials that were excluded.
I'm using it for partitioning helper classes where some methods need lots of code. This is quite an easy way of retaining readability as each file only deals with a portion of the class's functionality.
In VB you can use it to separate "normal" code from code that needs late binding via "Option Strict Off".
In C# I only use it for unusually large classes.
The LINQ to SQL designer uses it extensively to split custom behaviors (partial methods) outside of the mapping class.
In short, its main purpose is for code generators.
Hope this helps.
I use partial classes and methods all the time with Linq2Sql. Otherwise I have never used it for anything besides UI/Code-behind classes.
One of the great things that I like about partial classes in linq2sql is that you can have the partial class inherit an interface and it will map the interface to the generated class. This is great if you have more than one Data provider and still want to use the same interfaces for all the Data access classes.
WPF uses partial classes extensively. The XAML generates a partial class that you can add to.
I use partial classes to reduce the merge pain with version control when I know that we would have several developers working on one class. For example, we often have our DAL class split into several partial class files. If you don't put them in different files, it's easy to get merge conflicts that take a while to fix when checked into version ctl.
When the develoment gets less chaotic as the class gets close to complete, we get rid of the partial files. We just use it to make VC/mulit-developer issues easier

Categories

Resources