how can I implement factory pattern using C++ class? - c++

I am working on a project which was mostly implemented using factory and facade patterns. However I am unable to understand as I do not have a clear concepts of how factory pattern works in C++. Can anybody suggest good sample program or link for the same.
Thanks
krissam

A good website for all design pattern queries is
Hudson Design Patterns
It pretty much has all GOF design patterns in it, but explains it in a way which is quite easy to understand. Also includes demos.

Wikipedia has a factory pattern page.
For simple cases there really is no trick. Just
Foo* createFoo() {
return new Foo();
}
It gets trickier when you want to do more than just use new. One good example is if the constructor takes a number of parameters, or if the objects need to be initialized somehow. In that case you can load up the factory with the requirements and not make the developer worry about them:
class BarFactory {
BarFactory(Dep* x, Depen* y) ...
getBar() {
return new Bar(x->SOME_METHODS, y->SOMETHINGELSE, ...);
}
}
In that example the the factory takes the confusion out of correctly making a Bar object, (imagine it took more arguments and they needed a lot of hand holding). This can be helpful when you've got an API with a lot of options that don't change or just a bad API.

The factory pattern works in all languages the same.
class NodeFactory {
SimpleNode createSimple() { return new SimpleNode(); }
ComplexNode createComplexNode() { return new ComplexNode(); }
};
A factory is just a class that has methods which create objects.
Angelo

Related

Coding to an interface without an additional use of the interface aside from mocking for tests?

I have been trying to apply TDD at work as of late and occasionally get hung up when I need to think about the best ways to mock. What I am working on involves a good deal of network requests and file system access so there doesn't seem to be anyway around mocking. From the GMOCK documentation my understanding is that my best options to mock classes are either through, "coding to an interface", or via templates.
Here are my 2 main questions regarding "coding to an interface", which afterward I will give examples to hopefully clarify what I am asking:
When I currently have no additional uses of an interface beside mocking/testing, does it still make sense to use this method?
So now if I go ahead with "coding to an interface", which I only did for mocking/testing. If instead of passing around that interface, I just pass around what I want to mock(who inherits from that interface), am I still "coding to an interface"? I bring this up because sometimes this feels more readable.
Sample code for #1...
class Thing {
bool IsInstalled(); // multiple filesystem calls, I want to mock this method
};
bool Install(vector<Thing>& thingsToInstall) // before "coding to an interface"
bool Install(vector<unique_ptr<IInstallable>>& thingsToInstall) // after "coding to an interface"
class Thing : public IInstallable {
bool IsInstalled() override;
};
class IInstallable {
virtual bool IsInstalled() = 0;
};
The behavior I am interested in mocking is whether or not these "Thing"s are installed or not. Based on that I may or may not do a network request(which I've already mocked). So instead of passing around a vector of "Thing" objects, I have to pass around a vector of unique_ptr to IInstallable(the behavior/interface I want to mock). It seems like a lot just so I can only test it and not even reuse the interface. I guess I want to know am I indeed "coding to an interface" here and this is just the way it is? Also could you elaborate on when it does and does not make sense to "code to an interface"?
Sample code for #2...
bool Install(vector<unique_ptr<IInstallable>>& thingsToInstall) // original "coding to an interface" method from above
So now that I am coding to an interface, seeing as how my only reason for passing around unique_ptrs to the interface was so I could test it. Is there any reason why I shouldn't just pass around unique_ptrs to my "Thing" which implements the IInstallable interface? I can then still directly inherit from "Thing" for my mock class. This also in my code feels more readable since I am passing around a type that feels more relevant to the surrounding code(Thing) instead of a more generic interface. But then am I even "coding to an interface" anymore? Or am I just completely destroying the purpose(besides testing) of "coding to an interface"?
This is what the final method would look like...
bool Install(vector<unique_ptr<Thing>>& thingsToInstall) // Thing still implements IInstallable, so I can mock Thing directly
Thank you anyone that takes the time to read this and respond! I greatly appreciate your help.
I think your main question is about this argument:
It seems like a lot just so I can only test it and not even reuse the interface.
But your coding to interface example seems not practice. Defining an interface really requires careful design, rather than "I want to mock it so it should be an interface".
So back to your example, what you should really consider is, what is the common interface for class Thing, yes it should have bool IsInstalled(); but what else?
Let's say your real class Thing has two function in practice, then you're going to define your interface like this:
class IThing {
virtual bool IsInstalled() = 0;
virtual void DoSomething() = 0;
};
And then you can implement it:
class Thing : public IThing{
bool IsInstalled() override;
void DoSomething() override;
};
And use it like this:
bool Install(vector<unique_ptr<IThing>>& thingsToInstall);
Now you have the opportunity to:
Use IThing in your functions;
Create Thing and pass IThing to the functions in your production code;
Create MockIThing and pass IThing to the functions in your test code.

Does the self-shunt testing pattern violate the Single Responsibility Principle?

I've used the self-shunt unit testing pattern a few times over the years. As I was explaining it to someone recently they argued that it violated the SRP. The argument is that the test class can now be changed for one of two reasons: when the test changes, or when the method signature on the interface that the test is implementing changes. After thinking about it for a while, it seems like this is a correct assessment, but I wanted to get other peoples' opinions. Thoughts?
Reference:
http://www.objectmentor.com/resources/articles/SelfShunPtrn.pdf
My take on this is that the test class technically violates the SRP, but it doesn't violate the spirit of SRP. The alternative to self-shunting is to have a mock class separate from the test class.
With the separate mock class you might think that it's all self contained and satisfies the SRP, however the semantic coupling to the mock class's attributes is still there. So, really, we didn't achieve any meaningful separation.
Taking the example out of the PDF:
public class ScannerTest extends TestCase implements Display
{
public ScannerTest (String name) {
super (name);
}
public void testScan () {
// pass self as a display
Scanner scanner = new Scanner (this);
// scan calls displayItem on its display
scanner.scan ();
assertEquals (new Item (“Cornflakes”), lastItem);
}
// impl. of Display.displayItem ()
void displayItem (Item item) {
lastItem = item;
}
private Item lastItem;
}
Now we make a Mock:
public class DisplayMock implements Display
{
// impl. of Display.displayItem ()
void displayItem (Item item) {
lastItem = item;
}
public Item getItem() {
return lastItem;
}
private Item lastItem;
}
public class ScannerTest extends TestCase
{
public ScannerTest (String name) {
super (name);
}
public void testScan () {
// pass self as a display
DisplayMock dispMock = new DisplayMock();
Scanner scanner = new Scanner (dispMock );
// scan calls displayItem on its display
scanner.scan ();
assertEquals (new Item (“Cornflakes”), dispMock.GetItem());
}
}
In practical terms (IMHO) the higher coupling of TestClass to DisplayMock is a greater evil than the violation of the SRP for TestClass. Besides, with the use mocking frameworks, this problem goes away completely.
EDIT I have just encountered a brief mention of self-shunt pattern in Robert C. Martin's excellent book Agile Principles, Patterns, and Practices in C#. Here is the snippet out of the book:
We can accomplish this by using an abstract interface for the database. One implementation of this abstract interface uses the real database. Another implementation is test code written to simulate the behavior of the database and to check that the database calls are being made correctly. Figure 29-5 shows the structure. The PayrollTest module tests the PayrollModule by making calls to it and also implements the Database interface so that it can trap the calls that Payroll makes to the database. This allows PayrollTest to ensure that Payroll is behaving properly. It also allows PayrollTest to simulate many kinds of database failures and problems that are otherwise difficult to create. This is a testing pattern known as SELF-SHUNT, also sometimes known as mocking or spoofing.
So, the guy who coined the SRP (which is talked about in great detail in the same book) has no qualms using self-shunt pattern. In light of that, I'd say you are pretty safe from the OOP (Objected Orientated Police) when using this pattern.
In my opinion it is a violation, but a very minor one.
You test class is now a test class and a dependency for whatever you are testing.
However, is that a bad thing? For a couple of simple tests, probably not. As your number of test cases grows, you'll probably want to refactor and use a mock class to separate some of the concerns. (As the link you pasted says, self-shunt is a stepping stone to mocking). But if the number of test cases remains static and low, what's the problem?
I think a little pragmatism is required. Does it violate the SRP? Yes, but I'm guessing probably not as much as some of the code in the system you're testing. Do you need to do anything about it? No, not as long as the code is clear and maintainable, which for me is always the bottom line. SRP is a guideline, not a rule.
If the interface being implemented or shunted is changed, it's relatively likely that the test suite will have to change as well. So I don't really see it as a violation of SRP.
I prefer to have a little more control over the mocks/stubs that I'm creating. When I tried using the self shunt pattern I ended up making my test class more complex. By creating the mocks as locals within a test method I ended up having cleaner code.
FWIW unless you're using something powerful like C# (or python or an equivalent) your test code will change when you change an interface.

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.

Advice on wrapping third party libraries

I have been working a year now as a software developer for a at the computer-vision department of a company. My main job is integration of third-party software into a framework, so i usually end up writing wrapper libraries because a lot of this third party software does not work the way we want it to work(not thread safe, pain in the a** to use etc.).
Normally i just wrap the whole library and guard the calls to the library with mutual exclusions(thread safety is somehow the major problem with most extern libraries). I really enjoy doing this, as it puts you into a lot of interesting situations and you get to see a lot of interesting code. However i often think that i am not doing it properly or that my implementation is not really good. I feel like i am lacking some sort of design knowledge on how to properly do stuff like that.
Basically i want to know if there are any good guidelines or hints about designing a proper 'API ontop of broken API', or if this is always bound to be quite hackish and ugly.
I will quote an answer to another question on here the other day:
Does your current method pass testing?
Is it fast enough?
If yes, keep doing what you are doing.
As an alternative
Just ensure your new API encompasses both the intended functionality and the conventional or accidental functionality of the original. Also ensure it presents a 'fit-for-purpose' re-presentation. Take a peek at the C++ wrapping of C libraries in FOSS projects such as GTK/GTK for C++ (which just wraps the former).
If the API is broken, fix it and submit a patch ... get involved with the third-parties (I am assuming having access to the source means they won't mind this) ... You could re-write some of their API to be 'wrapping friendly' and suggest they merge some changes. If there is a problem, be the one to fix it.
Not much to it, just wrap A with B and ensure B does what A was supposed to, or is used for.
The only thing that I can add to Aiden's response is that you should also look to replace code that requires explicit initialization and termination with RAII techniques. When I've been faced with providing a façade over APIs, I always seem to run into a class that looks like:
struct ADVERTISER {
/* a bunch of members here */
};
void adv_Initialize(ADVERTISER *adv, /* a bunch of arguments */);
void adv_DoStuff(ADVERTISER *adv);
void adv_Terminate(ADVERTISER *adv);
I've seen this wrapped in a C++ class in the following manner:
namespace wrapper {
class Advertiser {
public:
Advertiser(): inited_(false) {}
void initialize(/* a bunch of arguments */) {
terminate();
adv_Initialize(&adv_, ...);
inited_ = true;
}
void doStuff() {
validate();
adv_DoStuff(&adv_);
}
void terminate() {
if (inited_) {
adv_Terminate(&adv_);
inited_ = false;
}
}
protected:
void validate() {
if (!inited_) {
throw std::runtime_error("instance is not valid");
}
}
private:
ADVERTISER adv_;
bool inited_;
};
}
The problem is that the Advertiser class doesn't really make the API any easier to use or even cleaner IMHO. If you run into cases like this, then:
Use a fully parameterized constructor to ensure that invalid instances do not exist
Clean up all resources in the destructor
Write a copy constructor and assignment operator if they make sense or make them private and don't implement them.
My goal is to make sure that whatever API I am presenting/creating/wrapping works with our existing coding style. I also try to bend the API into a more OO style than it may currently be in. I have seen a number of what I call object-oriented C like the one that I presented above. If you want to make them really fit into C++, then make then truly object-oriented and take advantage of what C++ gives you:
Be careful to manage any state variables.
If actions like copying don't make sense, then hide them.
If there is any possibility of leaking resources, then find some way to prevent it from happening (usually employing RAII helps).
Restrict the creation of instances using constructors to eliminate invalid instances and other edge cases.

Is it OK to pass parameters to a Factory method?

One of the ways to implement Dependency Injection correctly is to separate object creation from business logic. Typically, this involves using a Factory for object creation.
Up until this point, I've never seriously considered using a Factory so I apologize if this question seems a little simplistic:
In all the examples of the Factory Pattern that I've run across, I always see very simple examples that have no parameterization. For example, here's a Factory stolen from Misko Hevery's excellent How To Think About the "new" Operator article.
class ApplicationBuilder {
House build() {
return new House(new Kitchen(
new Sink(),
new Dishwasher(),
new Refrigerator())
);
}
}
However, what happens if I want each house that I build to have a name? Am I still using the Factory pattern if I re-write this code as follows?
class ApplicationBuilder {
House build( const std::string & house_name) {
return new House( house_name,
new Kitchen(new Sink(),
new Dishwasher(),
new Refrigerator())
);
}
}
Note that my Factory method call has changed from this:
ApplicationBuilder builder;
House * my_house = builder.build();
To this:
ApplicationBuilder builder;
House * my_house = builder.build("Michaels-Treehouse");
By the way: I think the concept of separating object instantiation from business logic is great, I'm just trying to figure out how I can apply it to my own situation. What confuses me is that all the examples I've seen of the Factory pattern never pass any parameters into the build() function.
To be clear: I don't know the name of the house until the moment before I need to instantiate it.
I've seen quite a lot of examples that use a fixed set of arguments, like in your name example, and have used them myself too and i can't see anything wrong with it.
However there is a good reason that many tutorials or small articles avoid showing factories that forward parameters to the constructed objects: It is practically impossible to forward arbitrary number of arguments (even for a sane limit like 6 arguments). Each parameter you forward has to be accepted as const T& and T& if you want to do it generic.
For more complicated examples, however, you need an exponentially growing set of overloads (for each parameter, a const and a nonconst version) and perfect forwarding is not possible at all (so that temporaries are forwarded as temporaries, for example). For the next C++ Standard that issue is solved:
class ApplicationBuilder {
template<typename... T>
House *build( T&&... t ) {
return new House( std::forward<T>(t)...,
new Kitchen(new Sink(),
new Dishwasher(),
new Refrigerator())
);
}
};
That way, you can call
builder.build("Hello", 13);
And it will return
new House("Hello", 13, new Kitchen(new Sink(...
Read the article i linked above.
Not only is is acceptable, but it's common to pass parameters to a factory method. Check out some examples. Normally the parameter is a type telling the factory what to make, but there's no reason you can't add other information you need to build an object. I think what you're doing is fine.
I can't see why it would be wrong to add this parameter to your factory. But be aware that you shouldn't end up adding many parameters which might not be useful to all objects created by the factory. If you do, you'll have lost quite a lot of the advantages of a factory !
The idea of a factory is that it gives you an instance of a class/interface, so there is nothing wrong with passing parameters. If there were, it would be bad to pass parameters to a new() as well.
I agree with Benoit. Think of a factory for creating something like sql connections though, in a case like this it would be necessary to pass information about the connection to the factory. The factory will use that information to use the correct server protocol and so on.
Sure, why not..!?
The nice thing about passing parameters is that it allows you to hide the implementation of the concrete object. For example, in the code you posted you pass the parameters to the constructor. However, you may change the implementation so that they get passed via an Initiailze method. By passing parameters to the factory method you hide the nature of constructing and initializing the object from the caller.
Take a look at Loki::Factory, there's an implementation very much like it coming to Boost as well, however. Some example code i regularly use in different flavors:
typedef Loki::SingletonHolder< Loki::Factory< Component, std::string, Loki::Typelist< const DataCollection&, Loki::Typelist< Game*, Loki::NullType > > > > ComponentFactory;
This might seem a bit weird at first sight, however let me explain this beast and how powerful it really is. Basically we create a singleton which holds a factory, the out most parameters are for the singleton, Component is our product, std::string is our creation id type, after this follows a type list of the params which is required for creation of Components ( this can be defined using a macro as well for a less verbose syntax ). After this line one can just do:
ComponentFactory::Instance().CreateObject( "someStringAssociatedWithConcreteType", anDataCollection, aGamePointer );
To create objects, to register one just use ComponentFactory::Instance().Register();. There's a great chapter on the details in the book Modern C++ Design.