High Level Configuration of Constructor Injection in C++ - c++

My questions are specifically dealing with dependency injection through the constructor. I understand the pros/cons of service locator pattern, constructor/setter injection, and their flavors, however there is something I can't seem to get past after choosing pure constructor injection. After reading many materials for testable design, including a thorough perusing of Miško Hevery's blog (specifically this post) I'm at the following situation:
Assume I'm writing a C++ program, and I have correctly injected my dependencies through their constructors. For readability I have given myself a high-level object which has a single Execute() function called from main:
int main(int argc, char* argv[]) {
MyAwesomeProgramObject object(argc, argv);
return object.Execute();
}
Execute()'s responsibility is to simply wire up all required objects and kick off the highest level object. The highest level object requires a couple dependencies and those objects required a few objects and so on and so on, implying a function that looks like this:
MyAwesomeProgramObject::Execute() {
DependencyOne one;
DependencyTwo two;
DependencyThree three;
MidLevelOne mid_one(one);
MidLevelTwo mid_two(two, three);
// ...
MidLevelN mid_n(mid_dependencyI, mid_dependencyJ, mid_dependencyK);
// ...
HighLevelObject1 high_one(mid_one, mid_n);
HighLevelObject2 high_two(mid_two);
ProgramObject object(high_one, high_two);
return object.Go();
}
From what I take from Miško's blog (and I would ask him, but figured he wouldn't have time to get back to me), this is the only way to satisfy pure constructor injection of dependencies.
In the blog post mentioned, he states we should have factories on a per object lifetime level, but this is essentially what Execute is doing, making my code look identical to his example:
AuditRecord audit = new AuditRecord();
Database database = new Database(audit);
Captcha captcha = new Captcha();
Authenticator authenticator =
new Authenticator(database, captcha, audit);
LoginPage = new LoginPage(audit, authenticator);
Questions:
Is this the correct approach?
Is this a pattern that I'm not aware of (seems similar to Maven's context.xml)?
For pure constructor injection, do I simply suffer the cost of "upfront" allocation?

Note that your different examples are contradictory. At first you show creating objects on the stack, and your last example allocates objects.
Objects on the stack are somewhat dangerous, but just fine in most cases. The main problem is to give another object that has a longer lifetime than your function an object pointer when that object comes from the stack... when that long lived object tries to access the object on the stack after the function returned, you have a problem. If all the objects have a stack lifetime, then you're fine.
Personally, I started using shared pointers and I find that to be the ultimate in easing the management of a large number of objects.
std::shared_ptr<foo> foo_object(new foo);
std::shared_ptr<blah> foo_object(new blah(foo));
In this way blah can hold a copy of the foo shared pointer forever and everything works as expected, even between function boundaries. Not only that, the shared pointer is NULL on creation, and auto-deleted on deletion (when the last shared pointer is deleted, of course.) And you can use weak pointer in objects that do not need the pointer to always be set...
Otherwise, I think that what you are trying to do works to a certain extend. In my world, it is often that things get created at a later time so I need a setter. However, constructor injections are very useful to force the user to properly initialize your object (i.e. I often create read-only objects, no setters, which are 100% initialized on construction, very practical, very safe!)

Related

c++ new without storing object

I've taken over some legacy C++ code (written in C++03) which is for an application that runs on an RTOS. While browsing the codebase, I came across a construct like this:
...
new UserDebug(); ///<User debug commands.
...
Where the allocation done using new isn't stored anywhere so I looked a bit deeper and found this
class UserDebug
{
public:
///Constructor
UserDebug()
{
new AdvancedDebug();
new CameraCommand();
new CameraSOG();
new DebugCommandTest();
new DebugCommand();
// 30 more new objects like this
};
virtual ~UserDebug(){};
};
I dug deeper into each of the class definitions and implementations mentioned and couldn't find any reference to delete anywhere.
This code was written by the principal software engineer (who has left our company).
Can anyone shed some ideas on why you would want to do something like this and how does it work?
Thanks
If you look into the constructors of those classes you’ll see that they have interesting side effects, either registering themselves with some manager class or storing themselves in static/global pointer variables á la singletons.
I don’t like that they’ve chosen to do things that way - it violates the Principle of Least Surprise - but it isn’t really a problem. The memory for the objects is probably (but not necessarily) leaked, but they’re probably meant to exist for the lifetime of the executable so no big deal.
(It’s also possible that they have custom operator news which do something even odder, like constructing into preallocated static/global storage, though that’s only somewhat relevant to the ‘why’.)
If these objects created once they might be expected to have the lifetime of the application (similar to singletons) and thus should never be deleted.
Another way to capture pointer is through overloaded operator new: both global and class specific. Check if there are any overloads that implement some sort of garbage collection.

How can I mock a method with a return type of unique_ptr in Google Mock?

I have read Can Google Mock a method with a smart pointer return type? but it did not really give much of an answer.
I have a factory that returns unique_ptr instances. Returning unique_ptr is a requirement that cannot change without really good reason and a discussion with those above my pay grade (which I am willing to do if it plain turns out you should not be returning these things).
In the code being tested, there are three objects in question. The first is a handler of sorts. Using that handler, you can create the second object, which is the only real interesting one after everything is said and done. But creating that second one is a complex process that requires extra work done by the specific handler instance, as well as a factory (the third object) to take care of logic needed in creating Mr. Second regardless of handler requirements.
Here's the testing code in question (with class names changed in order to avoid HR hell):
class BarTest : public ::testing::Test
{
protected:
Bar foo;
};
TEST_F(BarTest, createFoo)
{
// Data used in this test
std::string fooName = "test";
MockFooFactory<int> fooFactory;
MockFoo<int>* foo = new MockFoo<int>;
// When createFoo is called, it should call the foo factory's construct method with the given
// fooName and a pointer to the calling bar
EXPECT_CALL(fooFactory, construct(fooName, &bar)).
WillOnce(::testing::Return(std::unique_ptr<Foo<int>>(foo)));
// Test it
std::unique_ptr<Foo<int>> returnedFoo = bar.createFoo(fooName, fooFactory);
// createFoo should return the foo returned by the factory's construct method
ASSERT_EQ(foo, returnedFoo.get());
}
As one might expect, upon compiling this (specifically with GCC) the compiler complains about using the deleted copy constructor. I do not think there is a way to finagle this around in order to impose move semantics (at the very least not through the admittedly naive approaches I tried), and just telling it to return the raw pointer and hoping it can wrap it up itself also failed (potentially naive as well), so I am stuck.
At this point I am really leaning towards making a fake, but I would like to give it one last shot with pure mocking. If there is some way I can get this return to work, that would be fantastic. Either way, I have full control over the mocking and testing, so as long as this case gets covered (hopefully without hackiness) how direct or indirect the approach is not a concern.
I know this post is very old and you've probably discovered the answer by now.
However, a new piece of information is that in April 2017, gmock introduced a new Action modifier "ByMove".
EXPECT_CALL(*foo_, Bar(_, )).WillOnce(Return(ByMove(some_move_only_object)));

Should I use a public pointer?

I am currently working on a game where I have a couple of classes which each handles their own gameobjects. For these classes to actually represent something in the game they need to use another class which is the animation_manager.
The animation_manager handles the loading, drawing and moving of objects on the screen and is created at startup.
What would be the smartest way of passing the manager to the classes which handles the gameobjects?
Should it be done by a public pointer, by assigning it to a static pointer in the object class which every gameobject inherits from or should I simply just pass it as a pointer to the gameobjects/objects class constructor?
I am using C++03 so no new fancy fixes :P
EDIT 1:
There has been a lot of good suggestions and I am thankful for that.
Now I will not use weak pointers since I dont need the object handlers to take care of the deletion of the pointer as its going to exist from the beginning to the end of the program.
Singletons wont fit my needs either as I dont want any class to have access to it.
One thing that came to mind when reading the replies is: Would it be a good idea to make a static reference for the anim_handler in the Object class which all the handling classes inherits from?
I'd prefer the passing by constructor.
This way you can establish an invariant (i.e. the manager is always present) whereas later setting a field does not ensure it's always done.
Like thomas just posted you should use a shared_ptr or something similar (if not using C++11).
I try not to use static fields (except for constants) since it prevents you to use different manager objects for each gameobject. (Think of a debugging/logging manager class, or another wrapped manager).
You can keep this shared manager object in a shared pointer which is added to C++11 (or you can use Boost library) standard as shared_ptr.
It has a reference counting mechanism such that you do not have to worry about the ownership and memory management of related object.
Every gameobject can keep a shared pointer member to your animation_manager.
If your animator_manager is a unique object, another approach could be defining it as a signleton, eventually removing the need for storing any reference to it in the gameobjects handling classes and using some sort of static method like animation_manager::getInstance() to use it.
The performance impact could be easily minimized by reducing the calls to the getInstance() method, but it really depends on your design, can't be sure it would fit.
you should give it as a reference (if possible a reference to a const), not a pointer. Only if you would have a class hierarchy of animation managers a pointer (if possible const to a const) would make sense. In the latter case, you should consider using boost's shared_ptr. If move to C++11 later, the changes to C++11's shared_ptr are minimal.
From the design point of view, you might also think about using an observer pattern, so the animation manager can decide on its own when it is the right time to render without having too much boilerplate code.
Passing a reference would be the most favorable way when thinking as a good software architect, because it will allow easier testing and mocking.
However, a game(engine) is - in my opinion - such a special case of software where "good patterns" can be counterproductive sometimes. You will nearly always end up in the situation that you need some manager classes everywhere.
You might want to look at the god-object anti-pattern, to make all common managers available globally. I use one(!) globally accessible instance of an "Application"-instance, which contains some bootstrapping code and references to the most common manager classes, like this:
// application.h
class CApplication {
void init(int argc, char **argv); // init managers & co here
void shutdown();
void run();
CMemoryManager * memory;
CSystemManager * system;
CAudioManager * sound;
CInputManager * input;
};
// globals.h
CApplication * app;
// main.c
#include "globals.h"
int main(int argc, char ** argv) {
app = new CApplication();
app->init(argc, argv);
app->run();
app->shutdown();
return 0;
}
// some_other_file.cpp
#include "globals.h"
void doSomething() {
// ...
app->input->keyDown(...);
// ...
}
Bad style? Probably. Does it work? For me it does. Feedback is also welcome as comment!
I'm adding another answer because it's quite a different approach, when compared with the previuos one.
First of all I should clarify that I'm not experienced in game programming! :)
Anyway, as I was suggesting in my previous comments, maybe, I would take a different route. Immagine that you have a "game field" with walls and other static elemnts, and a number of "actors", like monsters, the player alter ego and so on...
I would probably write an ancestor "Actor", subcalssing "Player" and "Enemy" classes, then subclassing "Enemy" into "Dragon", "Zombie", "Crocodile" and so on. Maybe Actor could have a bounch of common attributes, like "location", "speed", "strenght", "energy", "direction", "destination" and a status, say "moving", "sleeping", "eating the player", "being eated"...
A typical game iteration, could be something like:
1) get input from the player
2) call a method of the player actor object, something like:
player->move(east, fast);
3) cycle trough a list of actors to update their status, say:
for (int i(0); i < enemies.size(); i++) {
// Checks the player position in the gamefield and setup a strategy to eat him
enemies[i]->updateStatus(player, gamingField);
}
4) cycle trough the list of actors and move them:
animator->animate(player);
for (int i(0); i < enemies.size(); i++) {
animator->animate(enemies[i]);
}
5) check if something interesting has happened (the player has been eaten by the crocodile)
I mean: this is a totally different approach, but I think that isolating the actors logic could be a good idea, and you could avoid the original problem completely.
It seems to me that there are no explicit answer for this question, but rather multiple ways of doing it which each has their own opinion on.
In case anyone else have the same question I am going to list them below:
Shared_Pointer:
This method will keep track of the amount of used pointers pointing to the address and if that count hits zero, then it will deallocate the memory. Is available in C++11 and the boost library.
A shared pointer can be passed to other objects the same way as a normal pointer.
Suggested by ogni42
Passed by constructor:
A pointer or reference can be passed to the object when it is being constructed. The upside of using a reference is that the programmer can't accidentally use delete on the pointer.
Prefered by Onur.
Use of singletons
Singletons are an unique extern class which holds a pointer to the object which can be accessed through a function.
This was suggested by Albert
Global variables
Simply a globally declared variables. Personally I do not recommend these as they can become a mess as they become available even from code which you wont need them in.
Suggested by Sir PanCake
static variables
This is what I ended up using. I made it so that only objects which inherited from my Object class could access the anim_handler. The way I did this was by declaring Object a friend of my anim_handler and then I made the static variable to retrieve the handler protected
Anyways, thanks for the support everyone! I appreciates it a lot and I even learned something new! :)

Prototype Pattern

According to wikipedia prototype pattern is :
The prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
Avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
Avoid the inherent cost of creating a new object in the standard way (e.g., using the new keyword) when it is prohibitively expensive for a given application.
I saw certain demo codes of this pattern in C++ all of them are using copy constructor.
Can anyone explain how point number two applies(in general as well as in context of C++) as we are using copy constructor anyways in clone function. If it can be done without copy constructor then an example code snippet would be great.
You can copy without dynamic allocation. For example, here's a cloning that only happens in a local scope:
Foo prototype;
void local()
{
Foo x = prototype; // first copy
x.mutate();
Foo y = x; // another copy
}
No dynamic allocation is used, ever.
It is true that return new Foo(*this); also makes a copy, but what's more important is that that object is allocated dynamically. That's the cost that your article to which is alluding.
In a game I've been making in Java, I ran into an interesting situation that fit the bill of a prototype pattern quite well. You see, I had this Animation object that stored a container of images to flip through, as well as some other data that tracked how long since the last frame was rendered, which frame it was on, if the animation was running or not, etc.
I found that for multiple characters to use the same Animation object was causing problems. If two characters shared an animation, they would turn on and turn off the animation at conflicting times for each other. I would have guys standing still with walking animations, or moving with standing animations. Creation of the animation objects were costly and time consuming what with creating the sprites, setting the ammount of time they would display for, creating an interval queue of images, etc.
Instead, I made the Animation object a prototype object. If an Animation clones itself, It shares the original collection of frames with all other animations since those are immutable, but also expensive to construct. Instead the new objects would share this immutable base, but have their own information of which frame to draw and when.
Think of it like a projector. When it get's cloned, the new projector might have it's own information on if it's running or not, which frame it's on, etc, but it may be using the same piece of film that the original projector is using. The reason why they don't trip each other up is that the film is immutable. (and expensive to create)
In all honesty, the usage of the prototype in this manner is a great way to implement a flyweight pattern. Objects that share Objects that are expensive to create. If you "clone" them, they would be instantiated with their new transient state, but still share those expensive base objects with it's creator.
Calling the copy constructor for object which isn't use dynamic memory inside itself is much more faster then perform any allocation in dynamic memory via new. Because allocation in dynamic memory is a kind of system call.

Proxy pattern - Applicability & Examples

From here: http://www.oodesign.com/proxy-pattern.html
Applicability & Examples
The Proxy design pattern is applicable when there is a need to control
access to an Object, as well as when there is a need for a
sophisticated reference to an Object. Common Situations where the
proxy pattern is applicable are:
Virtual Proxies: delaying the creation and initialization of expensive
objects until needed, where the objects are created on demand (For
example creating the RealSubject object only when the doSomething
method is invoked).
Protection Proxies: where a proxy controls access to RealSubject
methods, by giving access to some objects while denying access to
others.
Smart References: providing a sophisticated access to certain objects
such as tracking the number of references to an object and denying
access if a certain number is reached, as well as loading an object
from database into memory on demand.
Well, can't Virtual Proxies be created by creating an individual function (other than the constructor) for a new object?
Can't Protection Proxies be created by simply making the function private, and letting only the derived classes get the accesses? OR through the friend class?
Can't Smart References be created by a static member variable which counts the number of objects created?
In which cases should the Proxy method be preferred on the access specifiers and inheritance?
What's the point that I am missing?
Your questions are a little bit abstract, and i'm not sure i can answer at all well, but here are my thoughts on each of them. Personally i dont agree that some of these things are the best designs for the job, but that isn't your question, and is a matter of opinion.
Virtual Proxies
I don't understand what you are trying to say here at all. The point of the pattern here is that you might have an object A that you know will take 100MB, and you don't know for sure that you will ever need to use this object.
To avoid allocating memory for this object until it is needed you create a dummy object B that implements the same interface as A, and if any of its methods are called B creates an instance of A, thus avoiding allocating memory until it is needed.
Protection Proxies
Here i think you have misunderstood the use of the pattern. The idea is to be able to dynamically control access to an object. For example you might want class A to be able to access class B's methods unless condition C is true. As i'm sure you can see this could not be achieved through the use of access specifiers.
Smart Referances
Here i think you misunderstand the need for smart pointers. As this is quite a complicated topic i will simply provide a link to a question about them: RAII and smart pointers in C++
If you have never programmed in a language like C where you manage your memory yourself then this might explain the confusion.
I hope this helps to answer some of your questions.
EDIT:
I didn't notice that this was tagged c++ so i assume you do in fact recognize the need to clean up dynamic memory. The single static reference count will only work if you only intend to ever have one instance of your object. If you create 2000 instances of an object, and then deleted 1999 of them none of them would have their memory freed until the last one left scope which is clearly not desirable (That is assuming you had kept track of the locations of all the allocated memory in order to be able to free it!).
EDIT 2:
Say you have a class as follows:
class A {
public:
static int refcount;
int* allocated_memory;
A() {
++refcount;
allocated_memory = new int[100000000];
}
~A() {
if(! --refcount) {
delete [] allocated_memory;
}
}
}
And some code that uses it:
int main() {
A problem_child; // After this line refcount == 1
while(true) {
A in_scope; // Here refcount == 2
} // We leave scope and refcount == 1.
// NOTE: in_scope.allocated_memory is not deleted
// and we now have no pointer to it. Leak!
return;
}
As you can see in the code refcount counts all references to all objects, and this results in a memory leak. I can explain further if you need, but this is really a seperate question in its own right.
I am no expert, but here are my thoughts on Virtual Proxies : If we control the initialization via a separate function say bool Create(); then the responsibility and control of Initialization lies with the client of the class. With virtual proxies , the goal is to retain creation control within the class, without client being aware of that.
Protection Proxies: The Subject being protected might have different kinds of clients, ones which need to get unprotected/unrestricted access to all Subject methods and the others which should be allowed access to a subset of methods hence need for Protection proxy.
A proxy is an object behaving as a different object to add some control/behavior. A smart pointer is a good example: it accesses the object as if you would use a raw pointer, but it also controls the lifetime of that object.
It's good to question whether there are alternatives to standard solutions to problems. Design Patterns represent solutions that have worked for many folks and have the advantage that there's a good chance that an experienced programmer coming to the code will recognize the pattern and so find maintaining the code easier. However, all designs represent trade-offs and patterns have costs. So you are right to challenge the use of patterns and consider alternatives.
In many cases design is not just about making code work, but considering how it is structured. Which piece of code "knows" what. You proposal for an alternative for Virtual Prozy moves (as fizzbuzz says) knowledge of creation from the proxy to the client - the client has to "know" to call Create() and so is aware of the life-cycle of the class. Whereas with the proxy he just makes an object that he treats as the worker, then invisibly creation happens when the proxy decides it makes sense. This refactoring of responsibility into the proxy is found to valuable, it allows us in the future to change those life-cycle rules without changing any clients.
Protection proxy: your proposal requires that clients have an inheritance relationship so that they can use protected methods. Generally speaking that couples client and worker too tightly, so we introduce a proxy.
Smart reference: no, a single static count is no good. You need to count references to individual instances.
If you carefully work through each case you will find there are merits to the design patterns. If you try to implement an alternative you start with some code that sems simpler that the design pattern and then discover that as you start to refactor and improve the code, removing deuplicationand so on you end up reinventing the design pattern - and that's a really nice outcome.