Are C#'s partial classes bad design?

C#.Netvb.net

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

There are two reasons that I would (and do) use partial classes.

  1. To separate auto-generated portions of the code (such as WinForms designer code or T4 output).
  2. 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: https://stackoverflow.com/questions/160514/partial-classes-in-c

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

Solution 4 - C#

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

Solution 5 - C#

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

Solution 6 - C#

> 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

Solution 7 - C#

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.

Solution 8 - C#

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.

Solution 9 - C#

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.

Solution 10 - C#

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?

Solution 11 - C#

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 https://stackoverflow.com/questions/1050383/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.

Solution 12 - C#

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.

Solution 13 - C#

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.

Solution 14 - C#

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.

Solution 15 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondferraroView Question on Stackoverflow
Solution 1 - C#John FeminellaView Answer on Stackoverflow
Solution 2 - C#Jeff YatesView Answer on Stackoverflow
Solution 3 - C#AaronaughtView Answer on Stackoverflow
Solution 4 - C#Jon MView Answer on Stackoverflow
Solution 5 - C#JWPView Answer on Stackoverflow
Solution 6 - C#Simon BartlettView Answer on Stackoverflow
Solution 7 - C#Simon P StevensView Answer on Stackoverflow
Solution 8 - C#Jamie IdeView Answer on Stackoverflow
Solution 9 - C#Robert DavisView Answer on Stackoverflow
Solution 10 - C#sumit bishtView Answer on Stackoverflow
Solution 11 - C#JustinView Answer on Stackoverflow
Solution 12 - C#JulesView Answer on Stackoverflow
Solution 13 - C#Scott LawrenceView Answer on Stackoverflow
Solution 14 - C#David T. MacknetView Answer on Stackoverflow
Solution 15 - C#Teoman shipahiView Answer on Stackoverflow