What does "Depth of Inheritance" mean for methods? - c#

I have just installed the Visual Studio Power Tool for code analysis and the viewer for the results. Great tools, by the way!
When I click "Analyze Solution" I get the results:
Maintainability
Cyclomatic Complexity
Depth of Inheritance
Class Coupling
Lines of Code
I understand what these all mean, except that there are different values of "depth of inheritance" for each method in a class, and a larger one for the class.
Does anyone have an explanation of what this might be saying?

As each derived class extends the previous class, it adds additional functionality. It can add properties or methods that didn't exist in the previous base class. Now the the total set of methods is larger than it was for the base class. This process can be repeated when the derived class is derived from again.
So if you take the most derived class and pick a method A and follow it down to the base class that first implemented A, it might be a different deeper class than if you pick method B and follow it down to the first base class that implemented B. This is why the depth of inheritance can be different for different methods.
If you take the class itself, it has a clear series of base classes and a clear depth of its own, independent of the depth of the methods, which are always the same or less the class itself.

Here is a great explanation (with pictures!) of Depth of Inheritance:
http://www.nayyeri.net/depth-of-inheritance-for-wpf-and-windows-forms-applications

Related

Can't abstract replace partial?

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

Should composition be used exclusively over inheritance or are there cases when it should not?

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.

Base-Class implementation considerations

I wrote a class to do something and after a while I found that many other classes share the functionality so decided to implement a base-class (abstract in C#) and put all shared into it.
Since it's not possible to instantiate such a class then how to debug it ?
Is there any practical considerations for developing base-classes ?
Debugging the abstract class
There is nothing preventing you from debugging the abstract class, when debugging your child classes the debugger will automatically redirect you to parent class's implementation as required.
Designing class hierarchies
Although simple to inherit in .NET, it can quickly become difficult to maintain if you don't have a clear class hierarchy.
Inheritance is not the only way to ensure re-use in OO.
A couple of recommendations that might help:
Make sure your bases classes have a clear responsibility
Keep the depth of your inheritance low.
Tend to favour composition over inheritance. (Using interfaces might be a good choice)
If you need to test it, you can do one of two things:
1) You can have base classes that are not abstract, so the base can be instantiated and therefore tested.
2) In your test project you can make a mock wrapper around the base and test the mock.
Since it's not possible to instantiate
such a class then how to debug it ?
If you are asking how to actually test it then (i.e. Unit Test), I usually write a test class that inherits from the base class and test it that way. If you are asking about actually debugging then it is no different than any other class once you have instantiated it with a child class in a running application. Does that make sense?
Is there any practical considerations
for developing base-classes ?
Over the years I've heard two schools of though on this: 1) anything common put into a base class and 2) Don't make a base class if it is not a true inheritance. I tend to design/code to the former but #2 does have its merits in that it can make a design counter intuitive to some extent. Just my $0.02...
I would make a mock object that you make to inherit from your new abstract. You could even use a mocking framework to do this.
Keep it on hand to run your unit tests against, that is unless you use something like Rhino Mocks(my personal favorite mocking framework).
To debug the base class, create an instance of one of the derived classes and debug through that.
You might also consider creating another derived class which doesn't do anything except inherit from the base class so you can test it.
Firstly, it doesn't need to be abstract for your classes to inherit from it, and if it isn't abstract you can instantiate it. Otherwise just debug it form within a concrete implementation
You could create a derived version in your test fixture assembly (I'm assuming you are unit testing the base, hence the need to instantiate it individually) just for the purposes of testing the functionality of the base class. The derived version would provide any additional infrastructure needed to test the base. You may decide to create several derived versions to test different aspects of the abstract base.
You would debug it by using the derived classes that inherit from it. When debugging it you will need to keep in mind any changes that you make and review if the resulting behaviour is still shared by all derived classes.

Tool to coalesce Base and Derived C# Classes

Does anyone know of a tool or VS add-in that will allow me to take a base class and a derived class, and collapse them into a single 'flattened' class? Or is this too difficult an operation, given the need to cope with resolving overriden and hidden/new members?
Background: I am working on a project where we have a base class and a single derived class that was going to be the first of a few others.
Subsequent analysis work means that the other class will now not be necessary and the specialisation is just proving confusing for coders coming new to the codebase. I'd like to merge the base and the derived class to simplify things (and simplify the database mapping in nHibernate), but both are quite large - so I thought it would be worth checking if a tool could do the job.
As often, ReSharper can help you. There is an option (under menu: Refactor) called "pull members up" where you can select members to be moved to the base class.
There is an option "push members down for the other direction, too.

Is there a way to derive from a class with an internal constructor?

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

Categories