The biggest argument I've seen so far for partial classes is in the case of auto-generated code.
From a Java perspective, I don't see why this can't simply be done using abstract classes, can't the auto-generated code simply be an abstract class with protected abstract methods that it expects the user to override?
Aside from the auto-generated code cases, every other case I saw was either extremely rare (and the coders were just using partial as a hack), or it can also be solved using abstract or some other concept that already exists.
Inheritance is observable on the compiled assembly while partial is not. This makes inheritance unsuitable for libraries where you need to control the surface area tightly. The .NET BCL could never use this for example.
It is also a hack because inheritance is not meant to stitch together classes. It is primarily meant as a means to create substitutability and abstraction.
partial is meant for exactly this use case. The parts of a partial class can refer to each other which is not possible with inheritance.
Partial methods allow you to create methods that might exist in the compiled result, or not. LINQ to SQL uses them to give you callback hooks into various parts of the DataContext and entity classes. If you don't use them there is no performance cost at all because partial methods that are declared but never defined are just deleted.
For me, partial classes is a way to devide classes into more logical parts. Sometimes cause they are partly auto generated, sometimes because they are really complex.
Abstract is for inheritage, and why use that when nothing is really "shared".
Related
I was reading OOPs Concepts from internet using articles.
In one of article, I have read following about abstraction:
If we have a method named "CalculatePrice" inside the "Billing" class,
we are not concerned about the calculations inside the
"CalculatePrice" method. We just pass the necessary parameters and get
the output. We hide the implementation of "Calculate Price".
so my question is : In C#, we are using dlls and namespace and calls the specific methods. can we say that, dlls and namespaces are the concept of Abstractions ??
Thanks
No.
You should generally just think of dll-files and namespaces as ways to organize your projects.
The abstraction of CalculatePrice consists simply of the "hiding" of it's logic inside the method. When another piece of code calls the method, it does not care what happens inside it - it is only interested in the result.
Abstractions in C# (and .Net in general) are made using things like Classes, Interfaces, Abstract Classes, and method and properties that are defined and/or implemented in these.
Your focus should be on these concepts, and on how they are used together in different "patterns" to solve various types of problems.
To expand just a little on your example: If CalculatePrice was defined in an interface, then calling code would "talk to" that interface, without caring about what was behind it. An implementation of that interface - the code that actually performs the logic - could be anything. It could change, and keep changing, as long as it fulfills the requirements (the "contract") defined in the interface, since that would allow the calling code to keep using it.. and that is how abstraction works in C#.
Interesting that there are four answers all saying "no". In reality, the answer is "sometimes". If the implementation of CalculatePrice relies on another class, which is marked as internal, then its assembly does form part of the abstraction, since internal classes are only accessible to other classes in that assembly.
Namespaces in .NET do not form part of any abstraction though. In other languages they can, as internal can be tied to namespaces, but that is not how .NET languages work.
Such information hiding is the most basic form of abstraction though. C#'s most powerful abstraction tools are interfaces, support for dependency injection and its treatment of methods as values. If you are interested in understanding more about abstraction in C#, they are the three areas to focus on.
so my question is : In C#, we are using dlls and namespace and calls the specific methods. can we say that, dlls and namespaces are the concept of Abstractions ??
No.
Recently I was considering a class that seems to become fat because of too many methods in it.
A legacy code...
That has many business logic-wise methods doing all types of CRUD on various 'Etntities'.
I was thinking
make this class partial
and then grouping all methods by their target entities they work on
and splitting them into separate physical files that will be part of the partial class
Question:
Can you list pros and cons of such a refactoring, that is making a fat concrete class a partial class and splitting it into slimmer partial classes?
One pro I can think of is the reduction of conflicts/merges in your source control. You'll reduce the number of parallel check-outs and the merging headaches that invariably come when the devs check-in their work. A big pro, I think, if you have a number of devs working on the same class quite often.
I think that you are talking only about simplicity to handle the class. Performance or behaving pros and cons shouldn't be because when compiled it should generate the same result:
It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.
Now answering pros and cons I can think in (only about simplicity):
Pro: less conflicts / merges if working in a team.
Pro: easier to search code in the class.
Con: You need to know which files handles each code or it can get a little annoying.
I would go for the refactor. Specially considering all facilities given by the IDE where you just have to click F12 (or any other key) to go to a method, instead of opening the file.
Splitting a large class into partial classes perhaps makes life easier in the short term, but it's not really an appropriate solution to the code bloat that your class is experiencing.
From my experience, the only benefit that splitting an existing large class up gives you is that it's easier to avoid having to constantly merge code when working with other developers on said class. However, you still have the core problem of unrelated functionality being packaged into one class.
It's better to treat the breaking down to partial classes as the the very first step in a full refactoring. If you're able to easily extract related methods and members into their own partial classes (without breaking things) then you can use this as the basis for creating entirely standalone classes and rethinking the relationship between them.
Edit: I should clarify that this advice is given under the assumption that your legacy code has unrelated functionality in one class as a result of years of "just add one more method here". There are genuine reasons for having functionality spread across partial classes, for example, I've worked on code before that has a very large interface in one file, but then has all the methods grouped into partial classes based on areas of product functionality - which I think is fine.
I would say Partial class would help to maintain the code and will be more helpful when we have legacy code to avoid more changes on the reference side. Later will help to refactor easily
If you're concerned about how to refactor a class, I suggest reading into SOLID design principles.
I think you should focus on Single responsibility principle (the S in SOLID), which states an object should only have one responsibility.
I think my answer is not directly answering your question whether using partial classes would be beneficial to you, but I believe if you focus on the SOLID design principles that should at least give you some ideas on how to organize your code.
I see partial classes only as a way of extended a class that's code was generated (and can be re-generated at any time) that you would like to extend without your custom code being overwritten. You see this with the Form generated code and Entity Framework DbContext generated code for example.
Refactoring a large legacy class should probably be done by grouping and separating out single responsibilities into separate classes.
In the example I'm thinking of I have about 4 lines of code that could be encapsulated by a function, and this function will surely be used in other classes in the same hierarchy.
I have the following options for reusing that code:
Copy paste the function around to the classes that need it.
Make a base class for the classes that need the function and put it there.
Make a class that contains the function which gets passed into the classes that need it through DI or is just a member of the class. (seems like major overkill)
Make a static utility class and put that method in it.
I definitely wouldn't do 1 or 4. I would have done 2 in the past but I'm trying to keep to the composition over inheritance principle so I'm leaning towards 4 however it seems like a lot for something that will most likely never be used outside the hierarchy and is only 4 lines. I know this is very nitpicky but I want to figure out the right way to do it.
Inheritance was created for a reason. The fact that it has been overused doesn't mean that it doesn't have legitimate uses. The key is that whether you use it should not depend on whether you can get easy reuse out of it, but whether it makes sense for it to belong to the base class, based on what your base class represents.
Without better understanding what your classes are, and what the method is that you're trying to reuse, I can't give specific advice in your particular case. But think of it this way: When you say it will "most likely never be used outside the hierarchy," is that because it purely just doesn't make sense outside of that hierarchy? Or is it just that you don't think somebody's going to build something that happens to use this feature, even though it could conceivably make sense outside of the hierarchy?
If this method would make any sense outside of the specific hierarchy you're talking about, I would suggest approach #3.
And of course, all of this assumes that your class hierarchy is really a hierarchy in the first place. Another common abuse of inheritance is when people force a hierarchy on objects that don't need to be hierarchical in the context of their application.
I agree that composition is a better option than inheritance IN GENERAL. But composing your objects with some logic, perhaps via the strategy pattern, is a different issue than reusing the same code by multiple classes.
If those classes that need this functionality all have the same base class, then it makes sense to put it in the base class. It's not like the subclasses need to know the inner workings of the base class to make this call.
If various subclasses need different versions of this code, then creating behaviors via the strategy pattern (using composition) is the way to go. But I'm making an assumption that the same code satisfies every subclass.
I wouldn't do #4 because then that code is available to other classes that have no business calling it. If the code is in the base class, then you can make it protected and therefore only available to the classes that need it.
if such function arguments are going to be fields of the classes, than it is intended to be operating on your class state and thus should be a member of the base class that addresses such a manipulation.
if you operate on some data that makes sense outside of your hierarchy or from several branches of the hierarchy and meaning of the parameters is not bound to object state make it a function in a utility class.
If it's specifically related to your class hierarchy, use a base class. If not, use option 4. There is no need for composition here.
I'm still not really getting the upside of partial methods. Can anyone illustrate a problem that partial methods are ideally suited to solve?
From Partial Class and Methods (C# Programming Guide) on the MSDN:
A partial class or struct may contain a partial method. One part of the class contains the signature of the method. An optional implementation may be defined in the same part or another part. If the implementation is not supplied, then the method and all calls to the method are removed at compile time.
Partial methods enable the implementer of one part of a class to define a method, similar to an event. The implementer of the other part of the class can decide whether to implement the method or not. If the method is not implemented, then the compiler removes the method signature and all calls to the method. The calls to the method, including any results that would occur from evaluation of arguments in the calls, have no effect at run time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented.
Partial methods are especially useful as a way to customize generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs.
In my opinion, I would recommend to avoid using these unless you have a particular, specific need for them.
Essentially, the most useful purpose of partial methods is for a code generation system to provide an API for extending the capability of its properties and methods without using inheritance.
Take a look at any Linq to SQL data model for a quick example.
The generated code includes partial methods which, if implemented in your own partial class, grant the ability to execute validation logic, event notifications, etc. within existing properties.
What makes partial methods appealing is that, if you do not implement them in your own partial class, they are not emitted into the compiled code at all, which provides a modest efficiency boost.
Here's a decent blog entry that demonstrates the use of partial methods to inject validation logic:
http://www.davidhayden.com/blog/dave/archive/2007/07/24/LINQToSQLValidationEnterpriseLibraryValidationApplicationBlock.aspx
Generated code. Plain and simple this was the number one reason they were implemented. Look at something like WPF. The UI is done declaratively in XAML and the "code-behind" is in C#. Both parts are the same class split by using the partial class concept
As I understand it, one of the main benefits is the ability to have a code-generated "stub" that you can choose whether to implement. So your code-gen creates a partial method and calls some Validate method. In order to "plug in" your validation, you just implement the partial method. The "partial" keyword allows for a relatively clean development process.
I have read about partial methods in the latest C# language specification, so I understand the principles, but I'm wondering how people are actually using them. Is there a particular design pattern that benefits from partial methods?
Partial methods have been introduced for similar reasons to why partial classes were in .Net 2.
A partial class is one that can be split across multiple files - the compiler builds them all into one file as it runs.
The advantage for this is that Visual Studio can provide a graphical designer for part of the class while coders work on the other.
The most common example is the Form designer. Developers don't want to be positioning buttons, input boxes, etc by hand most of the time.
In .Net 1 it was auto-generated code in a #region block
In .Net 2 these became separate designer classes - the form is still one class, it's just split into one file edited by the developers and one by the form designer
This makes maintaining both much easier. Merges are simpler and there's less risk of the VS form designer accidentally undoing coders' manual changes.
In .Net 3.5 Linq has been introduced. Linq has a DBML designer for building your data structures, and that generates auto-code.
The extra bit here is that code needed to provide methods that developers might want to fill in.
As developers will extend these classes (with extra partial files) they couldn't use abstract methods here.
The other issue is that most of the time these methods wont be called, and calling empty methods is a waste of time.
Empty methods are not optimised out.
So Linq generates empty partial methods. If you don't create your own partial to complete them the C# compiler will just optimise them out.
So that it can do this partial methods always return void.
If you create a new Linq DBML file it will auto-generate a partial class, something like
[System.Data.Linq.Mapping.DatabaseAttribute(Name="MyDB")]
public partial class MyDataContext : System.Data.Linq.DataContext
{
...
partial void OnCreated();
partial void InsertMyTable(MyTable instance);
partial void UpdateMyTable(MyTable instance);
partial void DeleteMyTable(MyTable instance);
...
Then in your own partial file you can extend this:
public partial class MyDataContext
{
partial void OnCreated() {
//do something on data context creation
}
}
If you don't extend these methods they get optimised right out.
Partial methods can't be public - as then they'd have to be there for other classes to call. If you write your own code generators I can see them being useful, but otherwise they're only really useful for the VS designer.
The example I mentioned before is one possibility:
//this code will get optimised out if no body is implemented
partial void DoSomethingIfCompFlag();
#if COMPILER_FLAG
//this code won't exist if the flag is off
partial void DoSomethingIfCompFlag() {
//your code
}
#endif
Another potential use is if you had a large and complex class spilt across multiple files you might want partial references in the calling file. However I think in that case you should consider simplifying the class first.
Partial methods are very similar in concept to the GoF Template Method behavioural pattern (Design Patterns, p325).
They allow the behaviour of an algorithm or operation to be defined in one place and implemented or changed elsewhere enabling extensibility and customisation. I've started to use partial methods in C# 3.0 instead of template methods because the I think the code is cleaner.
One nice feature is that unimplemented partial methods incur no runtime overhead as they're compiled away.
Code generation is one of main reasons they exist and one of the main reasons to use them.
EDIT: Even though that link is to information specific to Visual Basic, the same basic principles are relevant to C#.
I see them as lightweight events. You can have a reusable code file (usually autogenerated but not necessarily) and for each implementation, just handle the events you care about in your partial class. In fact, this is how it's used in LINQ to SQL (and why the language feature was invented).
Here is the best resource for partial classes in C#.NET 3.0: http://msdn.microsoft.com/en-us/library/wa80x488(VS.85).aspx
I try to avoid using partial classes (with the exception of partials created by Visual Studio for designer files; those are great). To me, it's more important to have all of the code for a class in one place. If your class is well designed and represents one thing (single responsibility principle), then all of the code for that one thing should be in one place.