lundi 25 mai 2015

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:

  • have the object's constructor throw an exception
  • require the object provides a bool Validate(std::string x) method, which checks whether x is a valid argument string
  • Have the factory use the default constructor, and then call an initialisation method afterwards (begs the question: what if the init method fails?)
  • Set a bool member variable which, if true, means "this object is not in a sane state"
  • Some other option I've not thought of

Aucun commentaire:

Enregistrer un commentaire