I have a factory method pattern used to create classes and I'd like to validate the input parameters before proceeding to the actual creation. There are two classes that I am dealing with here, A and B, and they each have their own validation. Given that I am already passing the class type (A or B) in my creation template function, I'd like to use that type directly to tell which validation I need to use. I am considering to use template function specialization or dummy input parameter to do that, each with their own pros/cons. Please let me know if either one of them looks more reasonable, or if there are other options too. Thanks!
Oh, and I did consider making the validation as static methods of A or B, but that was not looking good because I am dealing with legacy code and moving that stuff around isn't too straightforward. I also showed this as an option below for completeness-sake though.
Template function specialization:
Pro: Able to use type passed into the FactoryCreateClass method directly for choosing validation
Con: Template method isn't being leveraged since there are only specializations
template <typename T>
void FactoryCreateClass (int, double)
(
bool bSuccess = ValidateBlock<T>(int, double);
if (bSuccess)
T* = T::CreateInstance();
)
template <typename T>
bool ValidateBlock (int double); // don't need an implementation here since
// all specialization require different validation
template <>
bool ValidateBlock<A> (int, double)
{
//do validation before creating A
}
template <>
bool ValidateBlock<B> (int, double)
{
//do validation before creating B
}
Dummy Variable:
Pro: Able to use type passed into the FactoryCreateClass method directly for choosing validation
Con: Unused dummy variable
template <typename T>
void FactoryCreateClass (int, double)
(
bool bSuccess = ValidateBlock(T /*dummy*/, int, double);
if (bSuccess)
T* = T::CreateInstance();
)
bool ValidateBlock (A/*dummy*/, int, double)
{
//do validation before creating A
}
bool ValidateBlock (B/*dummy*/, int, double)
{
//do validation before creating B
}
Static class method:
Pro: Able to use type passed into the FactoryCreateClass method directly for choosing validation
Con: Harder to make this type of change in legacy code
template <typename T>
void FactoryCreateClass (int, double)
(
bool bSuccess = T::ValidateBlock(int, double);
if (bSuccess)
T* = T::CreateInstance();
)
static bool A::ValidateBlock (int, double)
{
//do validation before creating A
}
static bool B::ValidateBlock (int, double)
{
//do validation before creating B
}