views:

819

answers:

13
+39  A: 

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

John Feminella
OK, you got me there, and you're right about designer generated code in Win and Web forms... But, IMO that's abolustely the only time I could ever see it being used. If you're following the SRP, you shouldnt need to ever type the partial keyword in your own classes... If this is the case, why doesnt MS put some different keyword that only allows these 'glueing' of classes to happen for code-generated tools, and send 'partial' to the same abyss where they put collapsing-an-if-statement?
dferraro
@dferraro: I disagree. Sometimes it is entirely valid to have a nested type within a class and it is good practise to give that nested type its own file.
Jeff Yates
@dferraro » Code is code is code. A compiler can't tell the difference between generated code and code that was typed by a human without some special designation -- which is more work, not less. Besides, as a general rule, it's better when languages allow you more flexibility and don't impose a particular mindset of the best way to do something. Part of good design is knowing that you can't possibly anticipate every situation in advance, and knowing when to break the rules.
John Feminella
I see what you mean on the first... but I disagree with your last statement... I think development platforms should be more like government (and government more like development platforms)... There should be restrictions (within reason) on what you can/can't do. This is why they removed multiple inheritence in .NET. And also removed the collapsing of all scope braces in VS... etc... but I suppose that's a topic for another thread =)
dferraro
@defarraro: Multiple inheritance wasn't removed from .NET - it was never added.
Jeff Yates
"Collapsing of scope braces" is an IDE feature, not a language one. Also, multiple inheritance wasn't included because of the fact that the tradeoff of functionality vs. complexity was too great, not because not having multiple inheritance is necessarily a good restriction. Finally, on a somewhat more personal note, I think there are lots of things that could stand to be _less_ like government, contrary to your assertion.
John Feminella
@Jeff, since you love so much about arguing over semantics, my username is *'dferraro'*.... Yes, Duh, C# never had multi-inheritence. But we all know what I meant - that *C#/Java the children of C++ did not include multi-inheritence because it encourged poor architecture design*... Ditto on the Scope Braces comment - like I really believed a compiler understood what collpasing code meant. Obviously I was talking about *Microsoft* removing that feature from *Visual Studio*... I thought we were all mature developers here at SO and I didn't have to spoon feed and over communicate... sigh...
dferraro
@dferraro: No, we didn't know what you mean; that's why we clarified! A lot of people come to SO with incorrect assumptions, so the smartest course of action is usually to figure out what those assumptions are first. We have no idea what you believe or don't believe without asking first, so we do.
John Feminella
I guess I see your point. Maybe I'm just a bit aggrivated at the fact I started this thread into the 900's of rep and came back monday to see im under 500. How the hell could that happen? I only have a few downvotes that I think I've always had. Did I piss off the SO gods or something?? lol
dferraro
@dferraro: There was a reputation recalculation recently to favor answers over questions. You can read more at blog.stackoverflow.com.
John Feminella
@dferraro: I apologise for the typo and my unprofessional immaturity. Thank you for setting the example.
Jeff Yates
+2  A: 

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
Simon Bartlett
But this isn't *explicitly* using them - it's all behind the scenes. I believe that the intent of the question was to determine a time when you would do so outside of the automatic behavior of the development environment.
David T. Macknet
+7  A: 

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: http://stackoverflow.com/questions/160514/partial-classes-in-c

Jeff Yates
I also used partials for the second reason.
Dykam
hmm... never thought of this before, using it for a nested class. But I digress... how often are nested types very complicated. In fact 2 classes should both be simple enough to fit in one file IMO! =P
dferraro
It happened to me quite a lot that I need classes which inherit the parent class, and only differ in functionality. The parent class exposes methods returning it's own type.
Dykam
+3  A: 

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.

Aaronaught
A: 

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 http://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.

Kragen
@Kragen: Microsoft Patterns and Practices use partial classes in, for instance, the Web Service Software Factory (http://codeplex.com/sf). It is used here to separate generated from hand-written code. They are also used by DSLs generated by the DSL Toolkit.
John Saunders
-1 for **solely** emphasis. It was a feature important enough to change the grammar of C#; that at least implies that there was more than one reason.
Robert Davis
@Robert - there is a blog / article somewhere from a Microsoft developer about the design of partial classes. I'll try and find it...
Kragen
See my answer, above, for where they've been incredibly useful.
David T. Macknet
A: 

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.

Simon P Stevens
+1  A: 

Can you explain to me when there would be a legitimate reason to ever use a partial class?

+1 for Simon Bartlett. If you use any data mapping feature (Entity Framework, Linq to SQL) it generates for you the code relavente to your database. The generated code will be partial has if you can include more methode and properties to your generated class.

Polo
+1  A: 

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.

Jamie Ide
+2  A: 

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

Jon M
+1  A: 

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.

Robert Davis
+1  A: 

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.

Jules
Can you provide a code snippet for this? Also: couldn't you have simply declared whatever variables as `Object` rather than whatever you've done?
David T. Macknet
There's an internal control called PropertyGridView which is part of the PropertyGrid control. You can access this by using the Controls collection property of the PropertyGrid. In the PropertyGridView is a Public property called GetScrollOffset. By treating the PGV as an object, with option Strict off, I can get hold of the scroll offset. ie. pgv as object = pg.Controls(2); (strict off); scrollOffset = pgv.GetScrollOffset.
Jules
+1  A: 

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.

Scott A. Lawrence
A: 

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.

David T. Macknet