Base-Class implementation considerations - c#

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.

Related

Maintenance cost of unit tests which mock abstract classes

Mocking abstract classes seems appealing at first, however some change in the constructor of the abstract class can broke unit tests where the mock of the abstract class is used. So unit test isolation is not 100%. I mean no one can guarantee that the constructor of the abstract class is simple. ( I mean do not throw, do not call DB or weird things like that). I know that the constructor should be simple, but I cannot guarantee that it will stay simple all the time.
Our legacy code base is abstract class heavy, and I don't really like to mock abstract classes.
This is the main reason I prefer interfaces, or wrapper interfaces around abstract classes. Is there a way to surround the call for the base class constructor? To be honest I have never ever created abstract class during TDD, but I cannot change the legacy part of our system.
I am biased to interfaces, but i am wondering that the issue I mentioned is real, or can be bypassed.
I would use interfaces over abstract classes as unless there's a good argument against it composition is preferable than inheritance.
But are you using a code productivity tool such as ReSharper or CodeRush? They allow you to refactor code including constructors efficiently which will save you hours in instances such as this.
I think the issue you mention is absolutely real. Mocking an abstract class and using its constructor or one of its concrete methods in the test really amounts to testing the class under test and the abstract class. It's not really a unit test any more. Mocks are already fragile animals, this only gives them an additional reason to screw your tests.
I guess the solution is pretty much contained in your question - use interfaces. It's best if you can make your legacy abstract classes implement these interfaces directly, but you can also wrap them and depend on the wrapper's interface rather than on the abstract class.
Being "interface biased" might not be a bad idea when it comes to dependencies. Interfaces define a contract describing what operations are available on a collaborator. Abstract classes (not purely abstract ones, which are pretty useless compared to interfaces) describe how a family of classes behave when executing a particular operation. You don't want to depend on the how and be coupled to details, you want to be coupled to high level abstractions.
As neoistheone commented, you can generate stubs from abstract classes with the Microsoft Fakes framework.

Is it recommended to mock concrete class?

Most of the examples given in mocking framework website is to mock Interface. Let say NSubstitute that I'm currently using, all their mocking examples is to mock interface.
But in reality, I saw some developer mock concrete class instead. Is it recommended to mock concrete class?
In theory there is absolutely no problem mocking a concrete class; we are testing against a logical interface (rather than a keyword interface), and it does not matter whether that logical interface is provided by a class or interface.
In practice .NET/C# makes this a bit problematic. As you mentioned a .NET mocking framework I'm going to assume you're restricted to that.
In .NET/C# members are non-virtual by default, so any proxy-based methods of mocking behaviour (i.e. derive from the class, and override all the members to do test-specific stuff) will not work unless you explicitly mark the members as virtual. This leads to a problem: you are using an instance of a mocked class that is meant to be completely safe in your unit test (i.e. won't run any real code), but unless you have made sure everything is virtual you may end up with a mix of real and mocked code running (this can be especially problematic if there is constructor logic, which always runs, and is compounded if there are other concrete dependencies to be new'd up).
There are a few ways to work around this.
Use interfaces. This works and is what we advise in the NSubstitute documentation, but has the downside of potentially bloating your codebase with interfaces that may not actually be needed. Arguably if we find good abstractions in our code we'll naturally end up with neat, reusable interfaces we can test to. I haven't quite seen it pan out like that, but YMMV. :)
Diligently go around making everything virtual. An arguable downside to this is that we're suggesting all these members are intended to be extension points in our design, when we really just want to change the behaviour of the whole class for testing. It also doesn't stop constructor logic running, nor does it help if the concrete class requires other dependencies.
Use assembly re-writing via something like the Virtuosity add-in for Fody, which you can use to modify all class members in your assembly to be virtual.
Use a non-proxy based mocking library like TypeMock (paid), JustMock (paid), Microsoft Fakes (requires VS Ultimate/Enterprise, though its predecessor, Microsoft Moles, is free) or Prig (free + open source). I believe these are able to mock all aspects of classes, as well as static members.
A common complaint lodged against the last idea is that you are testing via a "fake" seam; we are going outside the mechanisms normally used for extending code to change the behaviour of our code. Needing to go outside these mechanisms could indicate rigidity in our design. I understand this argument, but I've seen cases where the noise of creating another interface/s outweighs the benefits. I guess it's a matter of being aware of the potential design issue; if you don't need that feedback from the tests to highlight design rigidity then they're great solutions.
A final idea I'll throw out there is to play around with changing the size of the units in our tests. Typically we have a single class as a unit. If we have a number of cohesive classes as our unit, and have interfaces acting as a well-defined boundary around that component, then we can avoid having to mock as many classes and instead just mock over a more stable boundary. This can make our tests a more complicated, with the advantage that we're testing a cohesive unit of functionality and being encouraged to develop solid interfaces around that unit.
Hope this helps.
Update:
3 years later I want to admit that I changed my mind.
In theory I still do not like to create interfaces just to facilitate creation of mock objects. In practice ( I am using NSubstitute) it is much easier to use Substitute.For<MyInterface>() rather than mock a real class with multiple parameters, e.g. Substitute.For<MyCLass>(mockedParam1, mockedParam2, mockedParam3), where each parameter should be mocked separately. Other potential troubles are described in NSubstitute documentation
In our company the recommended practice now is to use interfaces.
Original answer:
If you don't have a requirement to create multiple implementations of the same abstraction, do not create an interface.  
As it pointed by David Tchepak, you don't want to bloating your codebase with interfaces that may not actually be needed.
From http://blog.ploeh.dk/2010/12/02/InterfacesAreNotAbstractions.aspx
Do you extract interfaces from your classes to enable loose
coupling? If so, you probably have a 1:1 relationship between your
interfaces and the concrete classes that implement them.
That’s probably not a good sign, and violates the Reused Abstractions
Principle (RAP).
Having only one implementation of a given interface is a code smell.
If your target is the testability, i prefer  the second option from David Tchepak's answer above.
However I am not convinced that you have to make everything virtual. It's sufficient to make virtual only the methods, that you are going to substitute.
I also will add a comment next to the method declaration that method is virtual only to make it substitutable for unit test mocking.
However note that substitution of concrete classes instead of interfaces has some limitations.
E.g. for NSubstitute
Note: Recursive substitutes will not be created for classes, as
creating and using classes can have potentially unwanted side-effects
.
The question is rather: Why not?
I can think of a couple of scenarios where this is useful, like:
Implementation of a concrete class is not yet complete, or the guy who did it is unreliable. So I mock the class as it is specified and test my code against it.
It can also be useful to mock classes that do things like database access. If you don't have a test database you might want to return values for your tests that are always constant (which is easy by mocking the class).
Its not that it is recommended, it's that you can do this if you have no other choice.
Usually well designed project rely on defining interfaces for your separate components so you can tests each of them in isolation by mocking the other ones. But if you are working with legacy code /code that you are not allowed to change and still want to test your classes then you have no choice and you cannot be criticized for it (assuming you made the effort to try to switch these components to interfaces and were denied the right to).
Supposed we have:
class Foo {
fun bar() = if (someCondition) {
“Yes”
} else {
“No”
}
}
There’s nothing preventing us to do the following mocking in the test code:
val foo = mock<Foo>()
whenever(foo.bar()).thenReturn(“Maybe”)
The problem is it is setting up incorrect behavior of class Foo. The real instance of class Foo will never be able to return “Maybe”.

Is there a reason to use abstract or interface except for coordination between developers? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Interface vs Abstract Class (general OO)
I can see their advantage in coordination of a developing team, or code that might be further developed by others.
But if not, is there a reason to use them at all? What would happen if I omit them?
Abstract – I'll be able to instantiate it. No problem. If it doesn't make sense – I won't.
Interface – I have that functionality declared in all classes deriving from it anyway.
Note: I'm not asking what they are. I'm asking whether they're helpful for anything but coordination.
Both are what I call contracts and can be used in the following fashion by an individual developer:
Abstract
Allows for polymophism of differing derived implementations.
Allows one to create base functionality which can be dictated or not that the derived class be required to implement.
Allows for a default operation to be runtime consumed if the derived does not implement or required to implement.
Provides a consistency across derived objects which a base class pointer can utilize without having to have the actual derived; hence allows generic operations on a derived object from a base class reference similar to an Interface in runtime operation.
Interface
Allows a generic pattern of usage as a defacto contract of operation(s).
This usage is can be targetted to the process in hand and allows for the
surgically precise operations for that contract.
Used to help with
factory patterns (its the object returned), mocking of data during
unit tests and the ability to replace an existing class (say from a
factory returning the interface) with a different object and it
doesn't cause any consumer of the factory any pain of refactoring due to the adherence of the interface contract.
Provides a pattern of usage which can be easily understood away from the static of the rest of the class's implementation.
Long story short are they required to get a job done? No.
But if you are into designing systems which will have a lifespan of more than one cycle, the upfront work by said architect will pay off in the long run whether on a team or by an individual.
++Update
I do practice what I preach and when handing off a project to other developers it was nice to say
Look at the interface IProcess which all the primary business classes adhere to. That process defines a system of goals which can help you understand the purpose and the execution of the business logic in a defined way.
While maintaining and adding new functionality to the project the interfaces actually helped me remember the flow and easily add new business logic into the project.
I think if you're not coordinating with others, it does two things
helps keep your from doing weird things to your own code. Imagine
your write a class, and use it in multiple projects. You may evolve
it in one project so that it is unrecognizable from it's cousin in
another project. Having an abstract class or interface makes you
think twice about changing the function signatures.
it gives you flexibility going forward - plenty of classic examples here. Use
the generic form of the thing you're trying to accomplish, and if
you decide you need a different kind later (streamreaders are a
great example, right?) you can more easily implement it later.
Abstract - you can instantiate a child of it, but what is more important, it can has its own non abstract methods and fields.
Interface - more "rough" one in regard of abstract, but in .NET you can have multiple inheritance. So by defining interface you can lead consumer of your interface(s) to subscribe to different contracts(interfaces), so present different "shapes" of specified type.
There are many reasons to use either construct even if you are not coordinating with anyone. The main use is that both actually help express the developper intent, which may help you later figure out why you choose the design you actually chose. They also may allow for further extensibility.
Abstract class allow you to define one common implementation that will be shared across many derived classes while delegating some of the behavior to the child classes. It allows the DRY (don't repeat yourself) principle to avoid having the same code repeated everywhere.
Interfaces expresses that your class implements one specific contract. This has a very useful uses within the framework, among which:
Use of library functionality that necessitate the implementation of some Interface. Examples are IDisposable, IEquatable, IEnumerable...
Use of constraints in generics.
Allow mocking of interfaces (if you do unit testing) whithout having to instanciate a real object.
Use of COM objects

Need of interfaces in c#

What is need of interfaces in c# ? as we are writing abstract method in interfaces. instead of that we can directly implement those methods in class.
Interfaces don't support implementation, so you cannot supply any default implementations as you can with abstract classes. Additionally, interfaces are not restricted to hierarchies, so they are more flexible than abstract classes.
You do not need to use interfaces in C#. They are useful and appropriate in some circumstances, but not in all circumstances. A handy rule of thumb that I use is that if, in your project, you only have one class that implements an interface, you do not need that interface.
Note: one possible counter to this rule of thumb is that you may need to write a second implementing class in the future, which may justify the use of the interface. I do not necessarily agree, as I think a considerable amount of time in programming is wasted anticipating future scenarios which never materialize.
You may want to read up on polymorphism.
For myself, I find a lot of use out of interfaces when I have similar objects but completely different implementations of the same methods.
Additionally, you can implement multiple interfaces but inherit only one abstract class. I find this very useful because my business objects have a better representation.
When writing any N-Tiered application which separates out business logic from the presentation I think you will start to find many uses for interfaces.
Interface is needed exactly as described in books: to define a contract between components. They are one of the best ways to expose certain functionality to other modules while preserving encapsulation.
For example:
1) try, without an interface, to expose some piece of functionality implemented in assembly 'A', to assembly 'B', with no actual implementation visible to assembly 'A'.
2) Even worse - if we consider .NET remoting scenarios, where the server must expose certain
functionality to the client, while the functionality is implemented and hosted on the server side. In this case an assembly is published to a client, where interfaces for the server-hosted classes are defined.
Think of Interfaces as contracts.
You create a contract that a class must follow. For example, if our Dog object must have a Walk method, it's defining class must implement this method.
In order to force every dog class (inherited or not) to implement this method, you must make them adhere to a contract i.e assign an interface which specifies that method.
An interface is a construct that enforces particular classes to follow strict rules of implementation.
The reason for this is that you end up with Dog objects (inherited or not) that now, by default, have a Walk method. This means you can pass these objects as parameters, safe in the knowledge that you can call the Walk method on any Dog class (inherited or not) and it will deffinately be implemented.
If you want to write testable code, you will usually need to employ interfaces. When unit testing, you may have ClassA which depends upon ClassB which Depends upon ClassC etc, but you only want to test ClassA. You certainly don't want to create a ClassC to pass to a ClassB just to instantiate ClassA.
In that case, you make ClassA depend upon IClassB (or some more generic name, most likely that does not imply anything about the ClassB implementation) and mock out IClassB in your tests.
It is all about dependency management for me.
You need interfaces when you want to think of a disparate set of classes as all being the same type of object. Say, for example, you have a set of classes that all read their configuration from a file. One way to handle this is to have all the classes implement the appropriate methods to read a configuration from a file. The trouble with this is that then any code that uses those classes and wants to configure them needs to know about all the different classes so that it can use the methods on them.
Another way is to have them all derive from a single base class. That way any code using the classes need only know about the base class -- it can treat any of the derived classes as the base class and use those methods defined in the base class to do the configuration. This isn't so bad, but it has the major drawback -- since C# doesn't support multiple inheritance -- of limiting your inheritance chain. If you want to be able to have the same sort of ability for some of the classes, but not all of them for a different set of behavior, you're stuck implementing it for all of them anyway. Not good.
The last way is to use interfaces to define the behavior. Any class wanting to implement the behavior need only implement the interface. Any class wanting to use the behavior need only know about the interface and can then use any class that implements it. Classes can implement any interface or even multiple interfaces so you have granular "allocation" of behavior among classes. You can still use base classes and inheritance hierarchies to provide the main behavior of a class in a shared way, but the class is also free to implement other interfaces to give itself more behavior and still retain the convenience of classes that use it to know only about the interface.
Interfaces allow implementers to use their own base class. With abstract classes, implementers are forced to use the given base class to implement the interface even if it actually makes more sense for the implementer to use a project-specific base class.
Interfaces are used to define the behaviour/properties of classes without specifying the implementation. If you begin thinking about classes as fulfilling roles rather than just being a bundle of methods and properties then you can begin assigning multiple roles to classes using interfaces - which is not possible using straight inheritance in C# as you can only inherit from a single class. By making clients of the classes depend on the interfaces (roles) rather than the class itself your code will be more loosely coupled and probably better designed.
Another benefit of this is if you are writing unit tests they are more likely to be focussed on behaviour rather than state. Coding against interfaces makes it very easy to make mock/stub implementations for this type of testing.
Not everything will need interfaces - but most things with behaviour probably (i.e. more than just a bundle of data) should have them IMHO as you'll always have two implementations: a real one in your application and one or more fake ones in your tests.
Interface is a contract that defines the signature of the functionality. So if a class is implementing
a interface it says to the outer world, that it provides specific behavior.
Example if a class is
implementing ‘Idisposable’ interface that means it has a functionality to release unmanaged
resources. Now external objects using this class know that it has contract by which it can dispose
unused unmanaged objects.
As presented by GoF 1st principle: Program to an interface not an implementation.
This helps in many ways. It's easier to change the implementation, it's easier to make the code testable and so on...
Hopes this helps.

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.

Categories