class definition and implementation in C# vs C++ - 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.

Related

How can I prevent methods from being added to a class?

I'm trying to find out if there's a way to stop functions/methods from being added (EDIT: by other developers) to a class for the case where the object is a Model or DTO which should not contain methods (to prevent 'abuse' of the Models/DTOs by others, who may try and add 'helper' methods etc).
Is there any way to achieve this?
Use reflection and write a unit test that fails if a model-class has methods.
Mark all you model classes with a custom attribute. Then make a unit test that uses reflection to load a given assembly, iterate all classes in that assembly and check that classes marked with the model attribute does not have methods. This should be fairly straight forward using reflection.
I believe you are trying to solve a procedural issue with code where you should be using communication.
Your colleagues (i assume) are operating on the code files with 'full trust' privileges. If they break that privilege you should open a dialogue. Use the change as an opportunity to educate them on the intended design. Perhaps they are correct and you will be educated!
I suggest simply making the intended design obvious in the class name and with a comment stating the intended nature. Perhaps quote the design document(s) that informed the class.
You cannot hinder anyone with full write-access to your code-base to do so. The only two things you may do to avoid it are create some CodeAnalysis-rule for FXCop as mentioned by Christian.K in the comments or by writing your DTO-class so that it is undoubtly a DTO that should not have any methods by using a unambigious name for the class and if this is not enough provide some code-comments that notifies the coder to do not so.
However you may need some kind of method if using collections e.g. where you will need some kind of comparision if two instances of your DTO are equal, so you have to provide at least an Equals- and GetHashCode-method.
You don't need to use a struct to prevent additions to a class. You can use the sealed keyword
public sealed class MyDTOObject { ... }
Now, you can not inherent a class and also prevent inheritance (which is essentially what you're asking). The very fact of inheriting MyDTOObject is creating a new class which is based off of not equal to, or restricted, or defined in any way by the implementation of MyDTOObject.
You can use an abstract class, to force derived classes to implement certain methods, but not the other way around.
If you want to prevent others from deriving from your class and implementing helper methods, you must use the sealed keyword, or mark the class internal.
You may prevent the class being extended or inherited by marking it final that way nobody would be able to extend your class and hence not being able to add any behavior. But stop and ask yourself whether you want to do that or not, because then you'd be signing an invisible contract that everything ever required by the class is written in the class and this class needs no further addition.
To be clear, I was talking in Java context.

Guidelines - extension methods vs partial class

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.

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.

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.

Best Practices: When not/to use partial classes

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.

Categories

Resources