I have the following two methods that (as you can see) are similar in most of its statements except for one (see below for details)
unsigned int CSWX::getLineParameters(const SURFACE & surface, vector<double> & params)
{
VARIANT varParams;
surface->getPlaneParams(varParams); // this is the line of code that is different
SafeDoubleArray sdParams(varParams);
for( int i = 0 ; i < sdParams.getSize() ; ++i )
{
params.push_back(sdParams[i]);
}
if( params.size() > 0 ) return 0;
return 1;
}
unsigned int CSWX::getPlaneParameters(const CURVE & curve, vector<double> & params)
{
VARIANT varParams;
curve->get_LineParams(varParams); // this is the line of code that is different
SafeDoubleArray sdParams(varParams);
for( int i = 0 ; i < sdParams.getSize() ; ++i )
{
params.push_back(sdParams[i]);
}
if( params.size() > 0 ) return 0;
return 1;
}
Is there any technique that I can use to move the common lines of code of the two methods out to a separate method, that could be called from the two variations - OR - possibly combine the two methods to a single method?
The following are the restrictions:
I know the following could (possibly?) be implemented as solutions but am really hoping there is a better solution:
The following is not a restriction but would be a requirement because of my teammates resistance:
A couple ideas come to mind, but here's what I think would be best:
namespace detail
{
void getParameters(const SURFACE& surface, VARIANT& varParams)
{
surface->getPlaneParams(varParams);
}
void getParameters(const CURVE& curve, VARIANT& varParams)
{
curve->get_LineParams(varParams);
}
}
template <typename T>
unsigned int getParameters(const T& curve, vector<double> & params)
{
VARIANT varParams;
detail::getParameters(curve, varParams);
SafeDoubleArray sdParams(varParams);
for( int i = 0 ; i < sdParams.getSize() ; ++i )
{
params.push_back(sdParams[i]);
}
return params.size() != 0;
}
What you do is delegate the task of getting parameters to some other function that is overloaded. Just add functions like that for each different type you have. (Note, I simplified your return statement.)
Extract Method. Everything after the lines you have marked as different is identical - so extract it as a method which is called from both of your original methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With