I have 2 custom server control classes. One inherits from TextBox and the other inherits from Label.
Both classes contain quite a lot of common code (various properties and attribute rendering logic), but the classes do contain some distinct code as well.
Ideally, the common code would be contained in an abstract class, and each custom control would inherit from that abstract class. This is not possible of course, because they already inherit from their respective base classes and c# doesn't support multiple inheritence.
How do I resolve the code duplication issue?
It depends on the exact functionality. If there is no way for them to inherit from the same place (as seems to be the case) then the best bet is to have a third class that contains the common functionality and include that in some way, either by having an instance of it in your control classes or by just calling static methods on it. Which I'd go for is probably dependant on what your code is and would hopefully be relatively obvious.
Related
Background
After spending a lot of time researching, I have not found any way of assigning multiple objects to PropertyGrid (Extended WPF Toolkit). My next idea is to create my own aggregator class that takes in selected objects and exposes their common properties to the outside world. I'll then assign (an instance of) this class to PropertyGrid. Any changes made by the user in PropertyGrid will be passed on to the selected objects by the aggregator class.
Question
Is there anything in the Framework (especially Reflection) that could help me with this task? All objects in my domain inherit from a common ancestor and add new properties of their own (or override ancestor versions). Class hierarchy is multiple levels deep.
UPDATE
For anyone else stuck in the same situation as me, I was able to finally solve PropertyGrid problem. See my other post for the solution.
Hope I can interpret what you want correctly.
One of the idea is using T4ToolBox to generate pre-compile class by scripting (which is also C# code in a template file).
Define your objects that want to be aggregate into xml.
Then you can use reflection to loop through all public method/properties in the objects (based on the xml) to find out the set of common methods
Generate an interface and (if you want) the corresponding concrete classes
One manual work after this is change your original object by implementing the newly generated interface.
if i inherit from a class such as System.Windows.Forms.Control and create System.Windows.Forms.NewControl, is there a way of forcing .NET to use my System.Windows.Forms.NewControl class as System.Windows.Forms.Control so that all built in controlls use my System.Windows.Forms.NewControl?
ie. i would like to make some base changes to how controls work, and i would like those changes to be reflected in ALL controls without having to subclass every single control type.
i know that extension methods will not work for this as they need to be called explicitly, and i am looking to alter properties as well as methods.
No, you cannot do anything like this. The idea behind OO is that people who write code adhering to the contract and behavior of an existing class can trust that the class will continue to behave how it's designed without worry about user interference. This isn't a dynamic language like Ruby.
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 have to write large amount of code which is going to be used in three asp.net pages.
I want to know the key points so that I can decide whether I should create Static Helper class , or create base class for common codes.
I am agree that creating single helper class vs creating multiple helper classes must be a careful job depending on various things like performance etc.., but the question still remain same , you can think me as a smart coder that can create perfect number of helper classes.
I think I am going to use these code only from these three asp.net pages.
Thanks for all your answers friends, but I need more inputs, can you please send more specific points.
Thanks.
If it is code that is being shared by all three ASP.NET pages and not by other code, a baseclass is a good idea.
The code is not exposed to the 'outside world' (by making the methods protected) and you define a context in which the methods should be used. They can only be called from an ASPX page that defines trough inheritance that it is-a certain base type where the methods make sense. A Helper method could be called from everywhere in your code by just passing the right parameters, even if this is conceptual invalid.
If it's code that's going to be called from different places (for example a ValidateEmail function) then a static helper class could help.
But if you opt for the helper class, you still have to decide how many helper classes you are going to create. Dumping all your helper functions in one class is probably not a good idea from maintenance perspective.
Create a base page and inherit from that and then put your helper method and properties on the base page.
I'm working with a 3rd party c# class that has lots of great methods and properties - but as time has gone by I need to extend that class with methods and properties of my own. If it was my code I would just use that class as my base class and add my own properties and method on top - but this class has an internal constructor. (In my opinion it was short sited to make the constructor internal in the first place - why limit the ability to subclass?)
The only thing I could think of was to create method / properties on my class that simply called into theirs - but it's acres of code and, well, it just doesn't "feel" right.
Is there any way to use this class a base class?
You ask: "Why limit the ability to subclass?"
Because designing for inheritance is tricky, particularly if you're designing for other developers to inherit from your class. As Josh Bloch says in Effective Java, you should design for inheritance or prohibit it. In my view, unless you have a good reason to design for inheritance, you shouldn't do so speculatively.
Does the class implement an interface which you could also implement (possibly by proxying most calls back to an instance of the original)? There's often no really elegant answer here - and the best solution will depend on the exact situation, including what you're trying to add to the class.
If you're not adding any more state - just convenience methods, effectively - then extension methods may work well for you. But they don't change what data an object is capable of storing, so if you need to add your own specialised data, that won't work.
Sounds like a perfect application for extension methods:
MSDN extension method docs
"Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type."
If the class has an internal constructor, and there are no public constructors, then that suggests that the designers did not intend for it to be subclassed. In that case, you can use encapsulation, or you can use extension methods.
Only if your class lives in the same assembly as the class you want to inherit from. An internal constructor limits the concrete implementations of the abstract class to the assembly defining the class. A class containing an internal constructor cannot be instantiated outside of the assembly.
Resharper has a nice feature to create delegating members.
Here is a sample of what you can do with it. It takes a couple of seconds.
I will not discuss whether you can build your own Facade around that 3rd party class. Previous authors are right, the library could be designed in the way that will not allow this. Suppose they have some coupled classes that have singletons that should be initialized in specific order or something like this - there may be a lot of design mistakes (or features) that 3rd party developers never care about, because they do not suppose that you will use their library in that way.
But OK, lets suppose that building a facade is not an impossible task, and you have in fact only one problem - there are too many methods you have to write wrappers around, and it is not good to do this manually.
I see 3 solutions to address exactly that problem
1) I suppose that new "dynamic" types of .NET 4.0 will allow you to workaround that problem without having to write "acres of code"
You should incapsulate an instance of 3rd party class into your class as a privare member with dynamic keyword
Your class should be derived from Dynamic or implement IDynamicObject interface. You will have to implement GetMember/SetMember functions that will forward all calls to the encapsulated instance of 3rd party class
Well, c# 4.0 is a future, Let's see on other solutions:
2) Do not write code manually if you have significant number of public methods (say more then 100). I would write a little console app that uses reflection and finds all public members and then automatically generates code to call encapsulated instance. For example
public type MethodName(params)
{
this.anInstanceOf3rdPartyClass.MethodName(params);
}
3) You can do the same as 2, but with the help of existing reflection tools, for example RedGate .NET Reflector. It will help you to list all classes and methods signatures. Then, paste all this in Word and a simple VB macro will let you generate the same code as you could do in 2.
Remark: As soon as you are not copying the code, but only copying method signatures, that are publicly available, I don't think you will violate the license agreement, but anyway it worth to re-check