manx_shearwater
manx_shearwater

Reputation: 75

Best practices for abstract factory construction that fails

Background

Suppose we have an implementation of the abstract factory which is invoked as follows:

std::string ObjectName = "An Object Name";
std::string Args = "Argument passed directly to constructor by the factory";

std::unique_ptr<MyBaseClass> MyPtr(ObjectFactory::Instance().Construct(ObjectName,Args));

The factory uses a std::map to turn "An Object Name" into a constructor, which itself takes a std::string as an argument. The idea is that the user knows more about the constructed objects than I do, so I should get out of the way and let the user pass any information they want to the constructor.

Question

This works fine when Args is in exactly the form expected but I don't know the most idiomatic way of handling duff inputs. What should happen if a user supplies an invalid argument string?

I can think of the following:

Upvotes: 2

Views: 173

Answers (4)

FToDance
FToDance

Reputation: 315

What ever you do, do not throw an exception from a constructor (as per Item #10 in More effective C++), as the destructor will not be called. It leads to newbie memory leaks and forces users to worry about exception handling.

I would just assert and return a Null Object, with dummy factory method implementations, or return nullptr.

Upvotes: -3

Blindy
Blindy

Reputation: 67584

Throw an exception. You're constructing an object (albeit in a different way than just new), failure is an exception that needs to be handled if it can happen.

"Solution 2" has nothing to do with handling this issue, it's more of a how to determine bad input. For such it can be an acceptable solution, but again it has nothing to do with the question at hand.

Solution 3 leaves the object in an indeterminate state in case of failure, which is unacceptable.

Solution 4 is another way to do it, and the only way if you don't have exception support in your language, but we do. Exceptions in this case are strictly better in my opinion because failing to construct an object is an action so destructive it should require alternative code or the program to die.

Upvotes: 6

KABoissonneault
KABoissonneault

Reputation: 2369

The first solution is the standard solution for constructor failure. Solution #2 and #4 are pretty error prone (user might forget to check) Solution #3 doesn't solve the problem

If you're making a library or just writing code that might be re-used in a "no exceptions allowed" environment, you could consider returning std::unique_ptr{nullptr}. Even if it is also error prone, that's the other standard way of handling construction failure.

Upvotes: 2

Brahim
Brahim

Reputation: 838

Maybe the easiest way is to return a nullptr.

Upvotes: 0

Related Questions