How to test anonymous classes? - unit-testing

I believe you must be familiar with this idiom, which is sort of java's excuse for closures
//In the "Resource Manager" class
public void process(Command cmd){
//Initialize
ExpensiveResource resource = new ExpensiveResource();
//Use
cmd.execute(resource);
//Release / Close
resource.close();
}
//In the Client class...
manager.process(new Command(){
public void execute(ExpensiveResource res){
//Do things with the resource
}
});
I used this idiom/pattern a lot but recently I tried to test it, and It's giving me a headache...
How do you get to test in isolation the ResourceManager and the Client classes? I found that this tight-couples them so much that you cannot do it easily.
Ideas are appreciated.
Regards

I think that anonymous classes should be so small and simple that testing the structure including/using them should be good enough.
If you have something so complicated, big, important that you feel the need to test it make it a full class.

If you don't want to make the anonymous type a real type you can test, consider moving the code in its execute() function into another function that you can test. The anonymous type then becomes a humble object (http://xunitpatterns.com/Humble%20Object.html).
edit but you should continue finding a way to test the code in the anonymous function.
In a typesafe language like C#, this can be done by having the anonymous code call a virtual member function. The test specializes the class by overriding the virtual function call, checking it is called.
In a nontypesafe language like Javascript, the member function called is already virtual. So rather than create a derived type, you can overwrite the called member function with a recorded version.

Don't use anonymous inner classes much (if at all). Aside from being difficult to test, they are virtually impossible to reuse without copy and paste.
Most of the time, making them full classes allows more flexibility and improves your OO design (adding more classes almost always improves your design).
By the way, as you mentioned closures also have the same problem--difficult to reuse.

Related

Preferring non-member non-friend functions to member functions

This question title is taken from the title of item #23 in Effective C++ 3rd Edition by Scott Meyers. He uses the following code:
class WebBrowser {
public:
void clearCache();
void clearHistory();
void removeCookies();
//This is the function in question.
void clearEverything();
};
//Alternative non-member implementation of clearEverything() member function.
void clearBrowser(WebBrowser& wb) {
wb.clearCache();
wb.clearHistory();
wb.removeCookies();
};
While stating that the alternative non-member non-friend function below is better for encapsulation than the member function clearEverything(). I guess part of the idea is that there are less ways to access the internal member data for the WebBrowser if there are less member functions providing access.
If you were to accept this and make functions of this kind external, non-friend functions, where would you put them? The functions are still fairly tightly coupled to the class, but they will no longer be part of the class. Is it good practice to put them in the class's same CPP file, in another file in the library, or what?
I come from a C# background primarily, and I've never shed that yearning for everything to be part of a class, so this bewilders me a little (silly though that may sound).
Usually, you would put them in the associated namespace. This serves (somewhat) the same function as extension methods in C#.
The thing is that in C#, if you want to make some static functions, they have to be in a class, which is ridiculous because there's no OO going on at all- e.g., the Math class. In C++ you can just use the right tool for this job- a namespace.
So clearEverything is a convenience method that isn't strictly necessary. But It's up to you to decide if it's appropriate.
The philosophy here is that class definitions should be kept as minimal as possible and only provide one way to accomplish something. That reduces the complexity of your unit testing, the difficulty involved in swapping out the whole class for an alternate implementation, and the number of functions that could need to be overridden by sub-classes.
In general, you shouldn't have public member functions that only invoke a sequence of other public member functions. If you do, it could mean either: 1) you're public interface is too detailed/fine-grained or otherwise inappropriate and the functions being called should be made private, or 2) that function should really be external to class.
Car analogy: The horn is often used in conjunction w/ slamming on your brakes, but it would be silly to add a new pedal/button for that purpose of doing both at once. Combining Car.brake() and Car.honk() is a function performed by Driver. However, if a Car.leftHeadLampOn() and Car.rightHeadLampOn() were two separate public methods, it could be an example of excessively fine grained control and the designer should rethink giving Driver a single Car.lightsOn() switch.
In the browser example, I tend to agree with Scott Meyers that it should not be a member function. However, it could also be inappropriate to put it in the browser namespace. Perhaps it's better to make it a member of the thing controlling Web browser, e.g. part of a GUI event handler. MVC experts feel free to take over from here.
I do this a lot. I've always put them into the same .cpp as the other class member functions. I don't think there is any binary size overhead depending where you put them though. (unless you put it in a header :P)
If you want to go down this route the imlementation of clearEverything should be put in both the header (declaration) and implementation of the class - as they are tightly coupled and seems the best place to put them.
However I would be inclined to place them as a part of the class - as in the future you may have other things to clear or there may be a better or faster implementation to implement clearEverythingsuch as droppping a database an just recreate the tables

Patterns for making c++ code easy to test

Should you design your code to make testing easier? And if so how to design c++ code so that it is easy to test.
How do you apply dependency-injection in c++?
Should I implement the classes using a pure interface class as the base in order to simplify the creation of fake test objects?
That would force me into making a lot of virtual methods. Will that affect performance?
What else should I think about when designing for testability in c++?
Should I implement the classes using a pure interface class as the base in order to simplify the creation of fake test objects?
That would force me into making a lot of virtual methods. Will that affect performance?
A workaround I often use is to templatize the class instead of hiding it behind an interface. Then I can pass test/mock objects as template parameters when testing, and the real objects otherwise. That way, the performance hit of virtual functions is avoided.
Edit
Ok, a simple example:
With OOP and interfaces, you might write a function such as this:
void Foo(IBar& someBar) { ... }
This function takes a parameter which implements the IBar interface, and does something with it. If you want to pass in a dummy mock implementation, you simply write a mock object which inherits from IBar and pass that to Foo. Simple and straightforward.
But you can achieve the same thing with templates:
template <typename BarType>
void Foo(BarType& someBar) { ... }
... and that's it. The body of Foo can be pretty much unchanged. As long as the type passed to the function exposes all the members we need, it'll work, without having to formally inherit from an interface class, and without the overhead of virtual functions and runtime polymorphism.
Don't design too much up from the start, then write a test, then make it pass, but not more than that. Keep your functions very short. Look what you've done and refactor it. If you're going to write a comment, better put the code in question to a separate function with a good name.
And don't spend too much time thinking of patterns, that's a lot of science and little outcome, just write a test first and keep your code simple, then, surprisingly you don't need to write tests for it, you've done it already. And your code works.
Maximum cohesion and minimum coupling.
This will make your life easier with testing.
I think prime concern should be ...
Achieving Functionalities
Code Extensiblity
Code Resuablity
Code Maintainability

Best way to use a C++ Interface

I have an interface class similar to:
class IInterface
{
public:
virtual ~IInterface() {}
virtual methodA() = 0;
virtual methodB() = 0;
};
I then implement the interface:
class AImplementation : public IInterface
{
// etc... implementation here
}
When I use the interface in an application is it better to create an instance of the concrete class AImplementation. Eg.
int main()
{
AImplementation* ai = new AIImplementation();
}
Or is it better to put a factory "create" member function in the Interface like the following:
class IInterface
{
public:
virtual ~IInterface() {}
static std::tr1::shared_ptr<IInterface> create(); // implementation in .cpp
virtual methodA() = 0;
virtual methodB() = 0;
};
Then I would be able to use the interface in main like so:
int main()
{
std::tr1::shared_ptr<IInterface> test(IInterface::create());
}
The 1st option seems to be common practice (not to say its right). However, the 2nd option was sourced from "Effective C++".
One of the most common reasons for using an interface is so that you can "program against an abstraction" rather then a concrete implementation.
The biggest benefit of this is that it allows changing of parts of your code while minimising the change on the remaining code.
Therefore although we don't know the full background of what you're building, I would go for the Interface / factory approach.
Having said this, in smaller applications or prototypes I often start with concrete classes until I get a feel for where/if an interface would be desirable. Interfaces can introduce a level of indirection that may just not be necessary for the scale of app you're building.
As a result in smaller apps, I find I don't actually need my own custom interfaces. Like so many things, you need to weigh up the costs and benefits specific to your situation.
There is yet another alternative which you haven't mentioned:
int main(int argc, char* argv[])
{
//...
boost::shared_ptr<IInterface> test(new AImplementation);
//...
return 0;
}
In other words, one can use a smart pointer without using a static "create" function. I prefer this method, because a "create" function adds nothing but code bloat, while the benefits of smart pointers are obvious.
There are two separate issues in your question:
1. How to manage the storage of the created object.
2. How to create the object.
Part 1 is simple - you should use a smart pointer like std::tr1::shared_ptr to prevent memory leaks that otherwise require fancy try/catch logic.
Part 2 is more complicated.
You can't just write create() in main() like you want to - you'd have to write IInterface::create(), because otherwise the compiler will be looking for a global function called create, which isn't what you want. It might seem like having the 'std::tr1::shared_ptr test' initialized with the value returned by create() might seem like it'd do what you want, but that's not how C++ compilers work.
As to whether using a factory method on the interface is a better way to do this than just using new AImplementation(), it's possible it'd be helpful in your situation, but beware of speculative complexity - if you're writing the interface so that it always creates an AImplementation and never a BImplementation or a CImplementation, it's hard to see what the extra complexity buys you.
"Better" in what sense?
The factory method doesn't buy you much if you only plan to have, say, one concrete class. (But then again, if you only plan to have one concrete class, do you really need the interface class at all? Maybe yes, if you're using COM.) In any case, if you can forsee a small, fixed limit on the number of concrete classes, then the simpler implementation may be the "better" one, on the whole.
But if there may be many concrete classes, and if you don't want to have the base class be tightly coupled to them, then the factory pattern may be useful.
And yes, this can help reduce coupling -- if the base class provides some means for the derived classes to register themselves with the base class. This would allow the factory to know which derived classes exist, and how to create them, without needing compile-time information about them.
Use the 1st method. Your factory method in the 2nd option would have to be implemented per-concrete class and this is not possible to do in the interface. I.e., IInterface::create() has no idea exactly which concrete class you actually wish to instantiate.
A static method cannot be virtual, and implementing a non-static create() method in your concrete classes has not really won you anything in this case.
Factory methods are certainly useful, but this is not the correct use.
Which item in Effective C++ recommends the 2nd option? I don't see it in mine (though I don't also have the second book). That may clear up a mis-understanding.
I would go with the first option just because it's more common and more understandable. It's really up to you, but if your working on a commercial app then I would ask what my peers what they use.
I do have a very simple question there:
Are you sure you want to use a pointer ?
This question might seem unlogical but people coming from a Java background use new much often than required. In your example, creating the variable on the stack would be amply sufficient.

What's the proper "C++ way" to do global variables?

I have a main application class, which contains a logger, plus some general app configurations, etc.
Now I will display a lot of GUI windows and so on (that will use the logger and configs), and I don't want to pass the logger and configurations to every single constructor.
I have seen some variants, like declaring the main class extern everywhere, but that doesn't feel very object oriented. What is the "standard" C++ way to make elements in the main class accessible to all (or most) other classes?
Use the singleton design pattern.
Basically you return a static instance of an object and use that for all of your work.
Please see this link about how to use a singleton and also this stackoverflow link about when you should not use it
Warning: The singleton pattern involves promoting global state. Global state is bad for many reasons.
For example: unit testing.
It is not so bad idea to pass the logger and config to all the constructors if your logger and config is abstract enough.
Singleton can be a problem in the future. But it seams like a right choice in the project begin. Your choice. If your project is small enough - go with singleton. If not - dependency injection.
Why not use the system that's already in place? That is, redirect std::clog to output to a file and write to std::clog.
std::fstream *f = new std::fstream("./my_logfile.log")
std::clog.rdbuf(f->rdbuf());
std::clog << "Line of log information" << std::endl;
I'd agree with some kind of singleton approach. You definitely don't want to pass logger objects around all over the place. That will get very boring very quickly, and IMHO is a worse design than just having a plain global object.
A good test of whether you've got a good solution is the steps required to get the logging working in a function that needs it.
If you have to do much more than
#include "Logger.h"
...
void SomeFunction()
{
...
LOGERROR << "SomeFunction is broken";
...
}
...
then you are wasting effort.
Logging falls under the realm of 'separation of concern' as in aspect orient programming
Generally logging is not a function or concern of an object (for example, it does not change the state of the object; it is merely a mechanism for observing/recording the state, and the output is essentially disposable in most contexts)
It is an ephemeral and often optional side function that does not contribute to the operation of a class.
An object's method may perform logging, but the logging may be done there because it is a convenient place to do it or that point in the code execution stream is where one desires the state to be recorded.
Because C++ does not provide facilities for defining aspects, I tend to simply keep essentially external ephemeral objects like loggers global and wrap them in a namespace to sort of contain them. Namespaces are not intended for containment so this is kind of ugly, but for for lack of anything else it is convenient and is far less ugly and inconvienent than passing loggers in formal parameters or referencing them in all the objects you want to log. This also makes it easier to remove the logger if at some point I decide I no longer need the logger (I.e. if it was only used for debugging).
Don't know if this is helpful in your situation or not, but in MFC, there was/is an application class.
I use to throw things like this into that class.
I assume you are not using MFC, but if you have an application class or something similar, this might be helpful.
Why not use log4cxx?
Such problems are solved long ago and widely used by many.
Unless you're building some very special logging system of your own... In such case, I'd use Factory pattern which would create loggers for anyone interested (or giving away existing instance if it's singleton). Other classes would use factory to obtain the logger. Passing loggers in constructor parameters is a bad idea, because it couples your class with logger.
Why has no one thought of heritage and polymorphism? You could also use an abstract factory with that singleton ;)
Simply pass your main class into the constructor of the other classes that you want to have access to "everything"
Then you can provide access to the logger etc. via member properties.
(Forgive my C++ syntax, this is just a made-up language called "C++ confused by VB")
e.g.
Class App {
Private m_logger;
Private m_config;
Public logger() {
return m_logger;
}
Public config() {
return m_config
}
}
Class Window1 {
New( anApp ) {
}
....
}
I guess Service Locator will do. That you'll have to either pass around in constructors, or have a globally accessible static member function in some well-known location. The former option is much more preferable.
I would avoid the singleton pattern.
Too many problems when it comes to testing and all that (see What is so bad about singletons?)
Personally I would pass the logger etc into the constructor. Alternatively you can use a factory to create/pass a reference to the resource.

Extending an existing class like a namespace (C++)?

I'm writing in second-person just because its easy, for you.
You are working with a game engine and really wish a particular engine class had a new method that does 'bla'. But you'd rather not spread your 'game' code into the 'engine' code.
So you could derive a new class from it with your one new method and put that code in your 'game' source directory, but maybe there's another option?
So this is probably completely illegal in the C++ language, but you thought at first, "perhaps I can add a new method to an existing class via my own header that includes the 'parent' header and some special syntax. This is possible when working with a namespace, for example..."
Assuming you can't declare methods of a class across multiple headers (and you are pretty darn sure you can't), what are the other options that support a clean divide between 'middleware/engine/library' and 'application', you wonder?
My only question to you is, "does your added functionality need to be a member function, or can it be a free function?" If what you want to do can be solved using the class's existing interface, then the only difference is the syntax, and you should use a free function (if you think that's "ugly", then... suck it up and move on, C++ wasn't designed for monkeypatching).
If you're trying to get at the internal guts of the class, it may be a sign that the original class is lacking in flexibility (it doesn't expose enough information for you to do what you want from the public interface). If that's the case, maybe the original class can be "completed", and you're back to putting a free function on top of it.
If absolutely none of that will work, and you just must have a member function (e.g. original class provided protected members you want to get at, and you don't have the freedom to modify the original interface)... only then resort to inheritance and member-function implementation.
For an in-depth discussion (and deconstruction of std::string'), check out this Guru of the Week "Monolith" class article.
Sounds like a 'acts upon' relationship, which would not fit in an inheritance (use sparingly!).
One option would be a composition utility class that acts upon a certain instance of the 'Engine' by being instantiated with a pointer to it.
Inheritance (as you pointed out), or
Use a function instead of a method, or
Alter the engine code itself, but isolate and manage the changes using a patch-manager like quilt or Mercurial/MQ
I don't see what's wrong with inheritance in this context though.
If the new method will be implemented using the existing public interface, then arguably it's more object oriented for it to be a separate function rather than a method. At least, Scott Meyers argues that it is.
Why? Because it gives better encapsulation. IIRC the argument goes that the class interface should define things that the object does. Helper-style functions are things that can be done with/to the object, not things that the object must do itself. So they don't belong in the class. If they are in the class, they can unnecessarily access private members and hence widen the hiding of that member and hence the number of lines of code that need to be touched if the private member changes in any way.
Of course if you want to access protected members then you must inherit. If your desired method requires per-instance state, but not access to protected members, then you can either inherit or composite according to taste - the former is usually more concise, but has certain disadvantages if the relationship isn't really "is a".
Sounds like you want Ruby mixins. Not sure there's anything close in C++. I think you have to do the inheritance.
Edit: You might be able to put a friend method in and use it like a mixin, but I think you'd start to break your encapsulation in a bad way.
You could do something COM-like, where the base class supports a QueryInterface() method which lets you ask for an interface that has that method on it. This is fairly trivial to implement in C++, you don't need COM per se.
You could also "pretend" to be a more dynamic language and have an array of callbacks as "methods" and gin up a way to call them using templates or macros and pushing 'this' onto the stack before the rest of the parameters. But it would be insane :)
Or Categories in Objective C.
There are conceptual approaches to extending class architectures (not single classes) in C++, but it's not a casual act, and requires planning ahead of time. Sorry.
Sounds like a classic inheritance problem to me. Except I would drop the code in an "Engine Enhancements" directory & include that concept in your architecture.