I've noticed that when I'm doing TDD it often leads to a very large amount of interfaces. For classes that have dependencies, they are injected through the constructor in the usual manner:
public class SomeClass
{
public SomeClass(IDependencyA first, IDependency second)
{
// ...
}
}
The result is that almost every class will implement an interface.
Yes, the code will be decoupled and can be tested very easily in isolation, but there will also be extra levels of indirection that just makes me feel a little...uneasy. Something doesn't feel right.
Can anyone share other approaches that doesn't involve such heavy use of interfaces?
How are the rest of you guys doing?
Your tests are telling you to redesign your classes.
There are times when you can't avoid passing complex collaborators that need to be stubbed to make your classes testable, but you should look for ways to provide them with the outputs of those collaborators instead and think about how you could re-arrange their interactions to eliminate complex dependencies.
For example, instead of providing a TaxCalculator with a ITaxRateRepository (that hits a database during CalculateTaxes), obtain those values before creating your TaxCalculator instance and provide them to its constructor:
// Bad! (If necessary on occasion)
public TaxCalculator(ITaxRateRepository taxRateRepository) {}
// Good!
public TaxCalculator(IDictonary<Locale, TaxRate> taxRateDictionary) {}
Sometimes this means you have to make bigger changes, adjust object lifetimes or restructure large swaths of code, but I've often found low-lying fruit once I started looking for it.
For an excellent roundup of techniques for reducing your dependency on dependencies, see Mock Eliminating Patterns.
Don't use interfaces! Most mocking frameworks can mock concrete classes.
That's the drawback of mock based testing approaches. This is as much a test boundary discussion as it is about mocking. By having a 1:1 ratio of test cases to domain classes your test boundary is very small. A result of a small test boundary is a proliferation of interfaces and tests that depend on them. Refactoring becomes more difficult due to the number of interactions you are mocking and stubbing out. By testing clusters of classes with a single test, refactoring becomes easier and you use fewer interfaces. Beware, however that you can test too many classes at once. The more complexity your classes have, the more code paths you need to test. This can lead to a combinatorial explosion and you can't possibly test them all. Listen to the code and tests, they're telling you something about your code. If you see the complexity increasing, it's probably a good time to introduce a new Test Case and Interface/Implementation and mock it out in your original.
If you are feeling uneasy about the number of interfaces being passed into a particular class; then it is probably a sign that you are introducing too many disparate dependencies.
If SomeClass depends on IDependencyA, IDependencyB, and IDependencyC, this is an opportunity to see if you can extract out the logic that the class performs with those three interfaces into another class/interface, IDependencyABC.
Then when you are writing your tests for SomeClass, you only need to mock out the logic that IDependencyABC now provides.
In addition, if you are still uncomfortable; maybe it is not an interface you require. For example, classes that contain state (parameters being passed around, for instance) could probably just be created and passed around as concrete classes instead. Jeff's answer alluded to this, where he mentions passing into your constructor ONLY what you need. This provides less coupling between your constructs and is a better indication of the intent of your class's needs. Just be careful passing around data structures (IDictionary<,>).
In the end, TDD is working when you get that warm fuzzy feeling during your cycles. If you feel uneasy, watch for some of the code smells and fix some of those issues to get back on track.
Related
Rhino Mocks is tightly coupled with the design pattern of using dependency injection and constructor injection, but I typically don't follow the dependency-injection paradigm and don't like to re-architect my solution just for my test tool.
Take this scenario:
class MyClass{
public void MyMethod(...){
var x = new Something(...);
x.A();
x.B();
x.C();
}
}
Would it be quite typical and acceptable to instead do the following, since this is not a case where I would generally wish to inject the dependency - it can be considered part of MyClass' behaviour/logic.
class MyClass{
public void MyMethod(...){
var x = NewSomething(...);
x.A();
x.B();
x.C();
}
virtual protected Something NewSomething(...){
return new Something(...);
}
}
Now I can (I think) extend MyClass either as a concrete class in my test project, or using Rhino... right? Is this a)correct b)a reasonably sensible, commonplace way of doing things?
Another approach I can see other than DI could be that I actually have a ClassFactory class in my project which creates all instances as needed; then I find a way to mock/stub that in my tests. But this seems 'smelly' to me, though I'm aware it is a pattern some people use.
I have used this quite a few times when trying to make legacy code more testable, although it really likes to come back and bite you later.
Basically, mocks/fakes/testdoubles are your enemy. You should hate them and avoid them (Edit note: I'm not saying don't use them, I'm saying use them only when you HAVE to). It all follows from the paradigm that all code is bad code, and we should write as little code as necessary to complete the task. Having a bunch of test doubles overriding virtual methods makes your code very rigid. It makes it really painful to change a method signature, even if your production code only invokes the method in a single place, because your test doubles will also break. It also makes it painful to later on clean up the mess and actually inject the dependency (and yes, I would argue injecting stuff is Objectively Better(tm)).
What it comes down to is basically: Yes, doing this will make your code more testable, but without any of the benefits you usually get by testing. You wn't get better design, you'll have rigid code etc.
I won't really point any fingers though, since I like I said have used this on occasion just to get a test up to see if something works. It can be a temporary solution that is "good enough", but my final answer is "probably don't if you can at all avoid it (and still have tested code)".
You would be sacrificing the Single Responsability Pattern (SRP) with the method that you're suggesting, and arguably making your code harder to read, understand and maintain, there's a smell right there, before we even reach the talking about tests.
If you plan to run tests, and at the same time not follow SOLID principles , then where are you saving on time, readability, or agility? (I honestly would love to know).
What the DI principle allows you to do is to run your tests completely in isolation from your dependencies, which is exactly what you want to be doing.
The SOLID principles of OOP have many good arguments going for them, but I'm always open to learn and be wrong, but I must say, I may have been blinded by several years of SOLID code, and tens of thousands of green unit tests securing my projects.
Lately I've been trying to follow the TDD methodology, and this results in lot of subclasses so that one can easily mock dependencies, etc.
For example, I could have say a RecurringProfile which in turn has methods / operations which can be applied to it like MarkAsCancel, RenewProfile, MarkAsExpired, etc.. Due to TDD, these are implemented as 'small' classes, like MarkAsCancelService, etc.
Does it make sense to create a 'facade' (singleton) for the various methods/operations which can be performed on say a RecurringProfile, for example having a class RecurringProfileFacade. This would then contain methods, which delegate code to the actual sub-classes, eg.:
public class RecurringProfileFacade
{
public void MarkAsCancelled(IRecurringProfile profile)
{
MarkAsCancelledService service = new MarkAsCancelledService();
service.MarkAsCancelled(profile);
}
public void RenewProfile(IRecurringProfile profile)
{
RenewProfileService service = new RenewProfileService();
service.Renew(profile);
}
...
}
Note that the above code is not actual code, and the actual code would use constructor-injected dependencies. The idea behind this is that the consumer of such code would not need to know the inner details about which classes/sub-classes they need to call, but just access the respective 'Facade'.
First of all, is this the 'Facade' pattern, or is it some other form of design pattern?
The other question which would follow if the above makes sense is - would you do unit-tests on such methods, considering that they do not have any particular business logic function?
I would only create a facade like this if you intend to expose your code to others as a library. You can create a facade which is the interface everyone else uses.
This will give you some capability later to change the implementation.
If this is not the case, then what purpose does this facade provide? If a piece of code wants to call one method on the facade, it will have a dependency on the entire facade. Best to keep dependencies small, and so calling code would be better with a dependency on MarkAsCancelledService tha one on RecurringProfileFacade.
In my opinion, this is kind of the facade pattern since you are abstracting your services behind simple methods, though a facade pattern usually has more logic I think behind their methods. The reason is because the purpose of a facade pattern is to offer a simplified interface on a larger body of code.
As for your second question, I always unit test everything. Though, in your case, it depends, does it change the state of your project when you cancel or renew a profile ? Because you could assert that the state did change as you expected.
If your design "tells" you that you could use a Singleton to do some work for you, then it's probably bad design. TDD should lead you far away from thinking about using singletons.
Reasons on why it's a bad idea (or can be an ok one) can be found on wikipedia
My answer to your questions is: Look at other patterns! For example UnitOfWork and Strategy, Mediator and try to acheive the same functionality with these patterns and you'll be able to compare the benefits from each one. You'll probably end up with a UnitOfStrategicMediationFacade or something ;-)
Consider posting this questions over at Code Review for more in depth analysis.
When facing that kind of issue, I usually try to reason from a YAGNI/KISS perspective :
Do you need MarkAsCancelService, MarkAsExpiredService and the like in the first place ? Wouldn't these operations have a better home in RecurringProfile itself ?
You say these services are byproducts of your TDD process but TDD 1. doesn't mean stripping business entities of all logic and 2. if you do externalize some logic, it doesn't have to go into a Service. If you can't come up with a better name than [BehaviorName]Service for your extracted class, it's often a sign that you should stop and reconsider whether the behavior should really be extracted.
In short, your objects should remain cohesive, which means they shouldn't encapsulate too many responsibilities, but not become anemic either.
Assuming these services are justified, do you really need a Facade for them ? If it's only a convenient shortcut for developers, is it worth the additional maintenance (a change in one of the services will generate a change in the facade) ? Wouldn't it be simpler if each consumer of one of the services knows how to leverage that service directly ?
The other question which would follow if the above makes sense is -
would you do unit-tests on such methods, considering that they do not
have any particular business logic function?
Unit testing boilerplate code can be a real pain indeed. Some will take that pain, others consider it not worthy. Due to the repetitive and predictable nature of such code, one good compromise is to generate your tests automatically, or even better, all your boilerplate code automatically.
I'm aware of (and agree with) the usual arguments for placing unit tests in a separate assembly. However, of late I've been experiencing some situations where I really want to be testing private methods. The behind-the-scenes logic in question is complex enough that testing the public and internal interfaces doesn't quite get the job done. The testing against the class's public interface feels overwrought, and I see several spots where a few tests against privates would get the job done more simply and effectively.
In the past I've tackled these kinds of situations by making the stuff I need to test protected, and creating a subclass that I can use to get at it in the test framework. But that doesn't work so well on classes that should be sealed. Not to mention bloating the test framework with all that scaffolding.
So I'm thinking of doing this instead: Place some tests in the class, where they can get at the private members. But keep them out of the production code using '#if DEBUG`.
Does this seem like a good idea?
Before anybody asks...
The solution to OP's problem is to properly incorporate IoC with DI and eliminate the need of testing private method altogether (as Joel Martinez noted). As it's been mentioned multiple times, unit testing private members is not the way to go.
However, sometimes you just can't change the code (legacy systems, risk of breaking changes - you name it) nor you can use tools that allow private members testing (like Typemock, which is paid product). For such cases, you can either not test at all, or cut corners. Which I believe is situation OP's facing.
Leaving private methods testing discussion aside...
Remember you can use reflection to access and invoke private members.
In my opinion, placing conditional debugs in the class itself is rather bad idea - it adds noise (as in, something unrelated) to the class code. Sure, it will be gone in release, but you (and possibly other programmers) will have to deal with it on the daily basics.
I realize your idea might sound good on paper - simple test wrapped with conditional debug. But in reality, tests quickly turn out to use extra variables (those will also have to be placed in the class code), some utility (extra references, custom types), testing frameworks (even more references) and what not. This all will have to be somehow connected to the class code. Put that all together, and you quickly end up with an unmaintanable monster.
Are you sure you want to deal with that? Especially considering that throwing together simple reflection-based utility is probably not that hard.
Everything you're referring to can be solved with just two concepts: Single Responsibility Principle, and Dependency Injection. It definitely sounds like you need to simplify your classes. Mind you, that doesn't mean the class must offer less value, it just means that the internals need to be simpler and some functionality may have to be delegated to others.
If you need to test this method independently of the public API of the class, then it sounds like a candidate for being removed from the class itself.
You could say the class is dependent on the private method (as is arguably evident by the need to test it separately from the class public API).
If this dependency cannot be satisfied through testing the public API of the type alone then have the class instead delegate this dependency to another type. You can either instantiate this type internally or have this type injected / resolved.
This new type can then have its own unit tests, as it's public API will be expressing what was previously a private method.
I have seen code where every class has an interface that it implements.
Sometimes there is no common interface for them all.
They are just there and they are used instead of concrete objects.
They do not offer a generic interface for two classes and are specific to the domain of the problem that the class solves.
Is there any reason to do that?
No.
Interfaces are good for classes with complex behaviour, and are especially handy if you want to be able to create a mock or fake implementation class of that interface for use in unit tests.
But, some classes don't have a lot of behaviour and can be treated more like values and usually consist of a set of data fields. There's little point in creating interfaces for classes like this because doing so would introduce unnecessary overhead when there's little point in mocking or providing alternative implementations of the interface. For example, consider a class:
class Coordinate
{
public Coordinate( int x, int y);
public int X { get; }
public int y { get; }
}
You're unlikely to want an interface ICoordinate to go with this class, because there's little point in implementing it in any other way than simply getting and setting X and Y values.
However, the class
class RoutePlanner
{
// Return a new list of coordinates ordered to be the shortest route that
// can be taken through all of the passed in coordinates.
public List<Coordinate> GetShortestRoute( List<Coordinate> waypoints );
}
you probably would want an IRoutePlanner interface for RoutePlanner because there are many different algorithms that could be used for planning a route.
Also, if you had a third class:
class RobotTank
{
public RobotTank( IRoutePlanner );
public void DriveRoute( List<Coordinate> points );
}
By giving RoutePlanner an interface, you could write a test method for RobotTank that creates one with a mock RoutePlanner that just returns a list of coordinates in no particular order. This would allow the test method to check that the tank navigates correctly between the coordinates without also testing the route planner. This means you can write a test that just tests one unit (the tank), without also testing the route planner.
You'll see though, it's quite easy to feed real Coordinates in to a test like this without needing to hide them behind an ICoordinate interface.
After revisiting this answer, I've decided to amend it slightly.
No, it's not best practice to extract interfaces for every class. This can actually be counterproductive. However, interfaces are useful for a few reasons:
Test support (mocks, stubs).
Implementation abstraction (furthering onto IoC/DI).
Ancillary things like co- and contra-variance support in C#.
For achieving these goals, interfaces are considered good practice (and are actually required for the last point). Depending on the project size, you will find that you may never need talk to an interface or that you are constantly extracting interfaces for one of the above reasons.
We maintain a large application, some parts of it are great and some are suffering from lack of attention. We frequently find ourselves refactoring to pull an interface out of a type to make it testable or so we can change implementations whilst lessening the impact of that change. We also do this to reduce the "coupling" effect that concrete types can accidentally impose if you are not strict on your public API (interfaces can only represent a public API so for us inherently become quite strict).
That said, it is possible to abstract behaviour without interfaces and possible to test types without needing interfaces, so they are not a requirement to the above. It is just that most frameworks / libraries that you may use to support you in those tasks will operate effectively against interfaces.
I'll leave my old answer for context.
Interfaces define a public contract. People implementing interfaces have to implement this contract. Consumers only see the public contract. This means the implementation details have been abstracted away from the consumer.
An immediate use for this these days is Unit Testing. Interfaces are easy to mock, stub, fake, you name it.
Another immediate use is Dependency Injection. A registered concrete type for a given interface is provided to a type consuming an interface. The type doesn't care specifically about the implementation, so it can abstractly ask for the interface. This allows you to change implementations without impacting lots of code (the impact area is very small so long as the contract stays the same).
For very small projects I tend not to bother, for medium projects I tend to bother on important core items, and for large projects there tends to be an interface for almost every class. This is almost always to support testing, but in some cases of injected behaviour, or abstraction of behaviour to reduce code duplication.
Let me quote OO guru, Martin Fowler, to add some solid justification to the most common answer in this thread.
This excerpt comes from the "Patterns of Enterprise Application Architecture" (enlisted in the "classics of programming" and\or the "every dev must read" book category).
[Pattern] Separated Interface
(...)
When to Use It
You use Separated Interface when you need to break a dependency between two parts of the system.
(...)
I come across many developers who have separate interfaces for every class they write. I think this is excessive, especially for
application development. Keeping separate interfaces and
implementations is extra work, especially since you often need factory
classes (with interfaces and implementations) as well. For
applications I recommend using a separate interface only if you want
to break a dependency or you want to have multiple independent
implementations. If you put the interface and implementation
together and need to separate them later, this is a simple refactoring
that can be delayed until you need to do it.
Answering your question: no
I've seen some of the "fancy" code of this type myself, where developer thinks he's SOLID, but instead is unintelligible, difficult to extend and too complex.
There's no practical reason behind extracting Interfaces for each class in your project. That'd be an over-kill. The reason why they must be extracting interfaces would be the fact that they seem to implement an OOAD principle "Program to Interface, not to Implementation". You can find more information about this principle with an example here.
Having the interface and coding to the interface makes it a ton easier to swap out implementations. This also applies with unit testing. If you are testing some code that uses the interface, you can (in theory) use a mock object instead of a concrete object. This allows your test to be more focused and finer grained.
It is more common from what I have seen to switch out implementations for testing (mocks) then in actual production code. And yes it is wroth it for unit testing.
I like interfaces on things that could be implemented two different ways, either in time or space, i.e. either it could be implemented differently in the future, or there are 2 different code clients in different parts of the code which may want a different implementation.
The original writer of your code might have just been robo coding, or they were being clever and preparing for version resilience, or preping for unit testing. More likely the former because version resilience an uncommon need-- (i.e. where the client is deployed and can't be changed and a component will be deployed that must be compatible with the existing client)
I like interfaces on things that are dependencies worth isolation from some other code I plan to test. If these interfaces weren't created to support unit tests either, then I'm not sure they're such a good idea. Interface have a cost to maintain and when it comes time to make an object swappable with another, you might want to have an interface apply to only a few methods (so more classes can implement the interface), it might be better to use an abstract class (so that default behaviors can be implemented in an inheritance tree).
So pre-need interfaces is probably not a good idea.
If is a part of the Dependency Inversion principle. Basically code depends on the interfaces and not on the implementations.
This allows you to easy swap the implementations in and out without affecting the calling classes. It allows for looser coupling which makes maintenance of the system much easier.
As your system grows and gets more complex, this principle keeps making more and more sense!
I don't think it's reasonable for Every class.
It's a matter of how much reuse you expect from what type of a component. Of course, you have to plan for more reuse (without the need to do major refactoring later) than you are really going to use at the moment, but extracting an abstract interface for every single class in a program would mean you have less classes than needed.
Interfaces define a behaviour. If you implement one or more interfaces then your object behaves like the one or other interfaces describes. This allows loose coupling between classes. It is really useful when you have to replace an implementation by another one. Communication between classes shall always be done using interfaces excepting if the classes are really tightly bound to each other.
There might be, if you want to be sure to be able to inject other implementations in the future. For some (maybe most) cases, this is overkill, but it is as with most habits - if you're used to it, you don't loos very much time doing it. And since you can never be sure what you'll want to replace in the future, extracting an interface on every class does have a point.
There is never only one solution to a problem. Thus, there could always be more than one implementation of the same interface.
It might seem silly, but the potential benefit of doing it this way is that if at some point you realize there's a better way to implement a certain functionality, you can just write a new class that implements the same interface, and change one line to make all of your code use that class: the line where the interface variable is assigned.
Doing it this way (writing a new class that implements the same interface) also means you can always switch back and forth between old and new implementations to compare them.
It may end up that you never take advantage of this convenience and your final product really does just use the original class that was written for each interface. If that's the case, great! But it really didn't take much time to write those interfaces, and had you needed them, they would've saved you a lot of time.
The interfaces are good to have since you can mock the classes when (unit-) testing.
I create interfaces for at least all classes that touches external resources (e.g. database, filesystem, webservice) and then write a mock or use a mocking framework to simulate the behavior.
Why do you need interfaces? Think practically and deeply. Interfaces are not really attached to classes, rather they are attached to services. The goal of interface is what you allow others to do with your code without serving them the code. So it relates to the service and its management.
See ya
I'm wondering how I should be testing this sort of functionality via NUnit.
Public void HighlyComplexCalculationOnAListOfHairyObjects()
{
// calls 19 private methods totalling ~1000 lines code + comments + whitespace
}
From reading I see that NUnit isn't designed to test private methods for philosophical reasons about what unit testing should be; but trying to create a set of test data that fully executed all the functionality involved in the computation would be nearly impossible. Meanwhile the calculation is broken down into a number of smaller methods that are reasonably discrete. They are not however things that make logical sense to be done independently of each other so they're all set as private.
You've conflated two things. The Interface (which might expose very little) and this particular Implementation class, which might expose a lot more.
Define the narrowest possible Interface.
Define the Implementation class with testable (non-private) methods and attributes. It's okay if the class has "extra" stuff.
All applications should use the Interface, and -- consequently -- don't have type-safe access to the exposed features of the class.
What if "someone" bypasses the Interface and uses the Class directly? They are sociopaths -- you can safely ignore them. Don't provide them phone support because they violated the fundamental rule of using the Interface not the Implementation.
To solve your immediate problem, you may want to take a look at Pex, which is a tool from Microsoft Research that addresses this type of problem by finding all relevant boundary values so that all code paths can be executed.
That said, had you used Test-Driven Development (TDD), you would never had found yourself in that situation, since it would have been near-impossible to write unit tests that drives this kind of API.
A method like the one you describe sounds like it tries to do too many things at once. One of the key benefits of TDD is that it drives you to implement your code from small, composable objects instead of big classes with inflexible interfaces.
As mentioned, InternalsVisibleTo("AssemblyName") is a good place to start when testing legacy code.
Internal methods are still private in the sense that assemblys outside of the current assembly cannot see the methods. Check MSDN for more infomation.
Another thing would be to refactor the large method into smaller, more defined classes. Check this question I asked about a similiar problem, testing large methods.
Personally I'd make the constituent methods internal, apply InternalsVisibleTo and test the different bits.
White-box unit testing can certainly still be effective - although it's generally more brittle than black-box testing (i.e. you're more likely to have to change the tests if you change the implementation).
HighlyComplexCalculationOnAListOfHairyObjects() is a code smell, an indication that the class that contains it is potentially doing too much and should be refactored via Extract Class. The methods of this new class would be public, and therefore testable as units.
One issue to such a refactoring is that the original class held a lot of state that the new class would need. Which is another code smell, one that indicates that state should be moved into a value object.
I've seen (and probably written) many such hair objects. If it's hard to test, it's usually a good candidate for refactoring. Of course, one problem with that is that the first step to refactoring is making sure it passes all tests first.
Honestly, though, I'd look to see if there isn't some way you can break that code down into a more manageable section.
Get the book Working Effectively with Legacy Code by Michael Feathers. I'm about a third of the way through it, and it has multiple techniques for dealing with these types of problems.
Your question implies that there are many paths of execution throughout the subsystem. The first idea that pops into mind is "refactor." Even if your API remains a one-method interface, testing shouldn't be "impossible".
trying to create a set of test data
that fully executed all the
functionality involved in the
computation would be nearly impossible
If that's true, try a less ambitious goal. Start by testing specific, high-usage paths through the code, paths that you suspect may be fragile, and paths for which you've had reported bugs.
Refactoring the method into separate sub-algorithms will make your code more testable (and might be beneficial in other ways), but if your problem is a ridiculous number of interactions between those sub-algorithms, extract method (or extract to strategy class) won't really solve it: you'll have to build up a solid suite of tests one at a time.