Are partial C # classes a bad design?

I wonder why the concept of a "partial class" exists even in C # / VB.NET. I am working on an application, and we are reading a (actually very good) book that matches the development platform that we implement at work. In the book, the author provides a large code base / wrapper around the platform APIs and explains how he developed it by studying various topics of platform development.

In any case, the long story is short - it uses partial classes throughout as a way to fake multiple inheritance in C # (IMO). Why didn’t he just divide the classes into several, but the use of composition outside of me. It will have 3 'partial class files to compose its base class, each of which contains 3-500 lines of code ... And it does this several times in its API.

Do you find it warranted? If it were me, I would follow SRP and create several classes to handle the various required behaviors, and then create a base class that has instances of these classes as members (e.g. composition). Why did MS even include a partial class in the framework? They removed the ability to expand / collapse all the code at each level in C # (this was allowed in C ++), because it obviously just allowed us to use bad habits - a partial class, IMO, the same thing. I think my question is: can you explain to me when there will be a legitimate reason to ever use a partial class?

EDIT: I know there is no other choice for Web / WinForms. But beyond that? Why didn't MS just add a few keywords to glue the code? Or is there really a suitable design scenario?

I do not mean that it is a battle / war. I honestly want to know something here. When should partial classes be used in code development? Simple question, no need to close

thank

+64
design c #
Mar 19 '10 at 14:01
source share
15 answers

Can you explain to me when there will 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. For example, usually automatically generated form code comes from some constructor, but you usually want to add your own behavior to it. That way, if you regenerate part of the automatic code, you do not touch the part that has your specific extensions.

However, it is possible to have too much good. Some tips:

  • Do not make your classes partial for partial .

  • Do not put partial classes anywhere other than each other. If you need to go to a completely unrelated part of the project to see the second half of the class, you are probably mistaken.

  • Do not use partial as a method to hide the size of the class. If you break up your classes with partial because they are too large, you should return to the principle of single responsibility .

  • If you have three or more partial fragments for the same class, this is almost a guarantee that you are abusing partial. The second is a typical upper bound of reasonableness and is usually used to segment automatically generated code from handwritten code.

In any case, the long story is short - it uses partial classes throughout as a way to fake multiple inheritance in C # (IMO). Why he just did not break the classes into several, and the use of composition is beyond me. It will have 3 'partial class files to compose its base class, each of which contains 3-500 lines of code ... And it does this several times in its API.

Yes, this is definitely a clear partial abuse!

+90
Mar 19 '10 at 14:02
source share
— -

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

  • Separate automatically generated parts of code (for example, WinForms constructor code or T4 output).
  • To allow nested types their own file, while preserving the encapsulation your design needs.

Update
I see that some are not convinced of my second point, so let me give you an example; ListViewItemCollection in the framework. It is quite correctly nested under ListView , because it is used only for ListView , but for simplification of maintenance I would give it my own file using partial classes. I do not see this as a poor design or misuse of the partial keyword.

For a more detailed discussion, check that this duplicate: Partial classes in C #

+12
Mar 19 '10 at 14:11
source share

Another legitimate use of partial classes is to help reduce the clutter of the "monolithic web service" in WCF. You want to break it down into logical function groups, but you don't want to create many separate instances / endpoints of the service (apparently because they share state, resources, etc.).

Decision? Ask the service to implement several interfaces and implement each interface in its own partial class. Then map the different endpoints in the configuration to the same physical implementation. This makes the project much more convenient, but you still have one physical endpoint.

In some cases, I would point out this type of approach as bad practice due to SRP, but when you work with WCF services or web services in general, it is not so simple. You must balance internal design requirements from external consumption requirements.

+10
Mar 19 '10 at 14:12
source share

One of the less common ways can be to split a huge class into separate physical files to make life easier in terms of source control. I just joined a project that contains some extremely bloated web service classes that work with thousands of lines of code and with methods related to several different business functions.

Merging with different branches of functions is a nightmare because different teams make simultaneous unrelated changes in the same file. I can't split a web service without major changes, but splitting a class into partial classes preserves behavior accurately and fixes a whole bunch of merge problems.

I definitely do not encourage the above as a design choice, but for us it was a good quick win, and it shows that the particles are not evil all the time ...

+6
Mar 19 '10 at 14:52
source share

In the past, I used partial classes differently. As I learn more about programming and, in particular, the concept of “composition of preference over inheritance”, I easily see the need to reduce both for vertical inheritance and for overuse of partial classes.

Besides auto-generated code, I can't think of the good use of partial classes. Even if you use EF and need different metadata, they do not even recommend using partial metadata. In fact, if you try to duplicate any properties in another partial (just add metadata), you will get a compiler error.

The more we learn about refactoring and SOC (Problem Separation), the less focused our classes become. They are reused by default, which over time makes them bulletproof and easily tested. Just say “NO” for gigantic programs. Henry Ford recognized this concept in early 1900, when programmers began to study it 100 years later.

Use composition when you can ...

+4
Oct 07 '14 at 14:28
source share

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

Recent versions of Visual Studio use partial classes to separate automatically generated developer code from your own code.

ASP.NET example:

  • Page.aspx
  • Page.aspx.cs <- Your code
  • Page.aspx.Designer.cs <is a partial class that contains automatically generated code.

WinForms example:

  • Form1.resx
  • Form1.cs <- Your code
  • Form1.Designer.cs <- a partial class containing automatically generated code
+2
Mar 19 '10 at 14:08
source share

I completely agree with John's answer. But I would take one more step.

  • Do not make partial parts.

The only use of partial classes that I can think of as a “good design” is automatically generated code. Any other use almost certainly does not necessarily separate your class. (In fact, I see that Jeff's second point on nested classes is possibly a valid use)

Personally, I think this book you are reading sounds like a bad design, but think that it can just use partial classes so that it can simply defiantly split a part of the code into several bits, and not just represent the whole class in one go.

+2
Mar 19 '10 at 14:12
source share

I used partial classes to “physically” separate the methods of static access to data from the properties and methods of the business class in the active recording architecture. For example, we had partial classes of Company and CompanyData side by side. The advantage was that one file was POCO and the other only data access methods. This was a step towards removing data access to the repository classes in an obsolete application. I think it was a legitimate use, it certainly made the re-factoring process more clear.

+2
Mar 19 '10 at 14:19
source share

Another useful use for partial classes would be when implementing the Abstract factory pattern . Partial the factory root partial, and then put the actual factory methods in the same file as the factory class instance.

EDIT: Partial classes also work well for classes that interact with the configuration file. Place the code containing the configuration parameters next to the code that actually uses the configuration parameter.

+2
Mar 19 '10 at 15:35
source share

Just stumbled upon this thread while you took advantage of the partial class. I am in the process of converting a Java EE application to .NET based on Silverlight. I came across the following code at the view level:

 //------------------------------------------------------------------------------ // <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 auto-generated, what should I use? In addition, the code inside simply binds the various controls to their names. I do not admit that I have knowledge about Silverlight, but is this thing better not suitable for xaml?

+2
Aug 05 2018-11-11T00:
source share

A partial class exists in the .NET Framework solely so that Visual Studio developers (such as Asp.Net designer and Windows Forms designer) generate code / clutter with your classes, saving this generated code in a separate file.

(See .NET Partial Classes and Inheritance )

If you do something like this (generate code that should coexist with user-written code), you may also find partial classes useful, but I do not believe that Microsoft has ever offered partial classes as a language concept to be useful for everyone except the Visual Studio team.

Not so much that using Partial classes is a bad design - you just probably won't find a use for them.

+1
Mar 19 '10 at 14:12
source share

I used the partial class twice in VB.Net, and both times were for the rare case that I needed to bind late. Just create a partial class and enable the Strict Off option at the top.

+1
Mar 21 '10 at 0:53
source share

Just adding to the previous answers that mentioned the generated generated code from user code, I found partial classes useful for extending strongly typed datasets.

+1
Mar 29 '10 at 16:29
source share

There is a lot of discussion on this topic, and many people say that 1) it is a poor design for using partial classes, 2) that it is used for auto-generated code, and 3) that it should not replace this place of inheritance.

I have a situation in which partial classes look as if they come in handy: I ​​am creating a series of applications that will eventually be integrated into a set. All of them will have a basic form, which will provide some functions and several common components (for example, a form for displaying reports). Although I could define a base class and inherit it, it would mean a big mess when it came time to combine all the applications into a "corporate" version of the product.

Thus, partial classes are very useful, because I can simply include various partial classes in the combined version, while maintaining the ability to create separate standalone versions of the product. If I tried to accomplish this using inheritance, I would include each component that invoked its own version of common components (e.g. InvoiceReportViewer, PurchasingReportsViewer, etc.), and not just invoke ReportViewer and knew that Visual Studio would integrate everything bits for me.

+1
Jul 16 '10 at 10:23
source share

Another thing is that partial classes force you to create different file names that contain the same class name . For example, you have a FactoryClass, and you create partial versions of this type; Factory.designer.cs, Factory.data.cs, ​​and all of these files have a class called FactoryClass.

If you come to this question; there is best practice defined as:

The best practice, however, is to define one class for each file and provide the file with the same name as the class definition (or structure, etc.).

0
Aug 03 '15 at 22:00
source share



All Articles