I was wondering whether it was a good practice to define algorithm parameter settings as an independent class. I illustrate my question with the following codes:
using namespace std;
class Parameters
{
public:
Parameters():a_para_(0),b_para_(0) {};
~Parameters() {};
Parameters(const Parameters ¶)
{
a_para_ = para.a_para_;
b_para_ = para.b_para_;
}
void set_a_parameter(int a)
{
a_para_ = a;
}
void set_b_parameter(int b)
{
b_para_ = b;
}
private:
int a_para_;
int b_para_;
};
class Algorithm
{
public:
Algorithm() {};
~Algorithm() {};
void set(const Parameters ¶)
{
para_ = para;
}
void run()
{
}
private:
Parameters para_;
};
int main()
{
Parameters para;
para.set_a_parameter(3);
para.set_b_parameter(4);
Algorithm fun;
fun.set(para);
fun.run();
return 0;
}
The philosophy behind is that the parameter setting and algorithm implementation can be separated. I discussed this design strategy with an experienced programmer, and it seems that he prefer that the parameter setting and the algorithm should be mixed together as one class. I am therefore writing here for your advice: which one is better? Thanks!
Your question is very general, and there’s no general answer. It depends on the situation.
Often times you want to be able to decide at compile time the parameters of your algorithm (for instance, the size of a given buffer, or the dimension of a matrix, or the arity of a tree nodes). Usually these parameters don’t change for the lifetime of your algorithm “instance”, so to speak. In this context, it is usually good practice to turn your algorithm class into a template, and make these parameters the template parameters.
If the parameters must change during the algorithm lifetime, but their implementation are trivial, there’s no need to externalize them. If they are non trivial, and their implementation details may change the algorithm performance (ex: a matrix implementation based on arrays for dense matrices, or on linked lists for sparse ones), then I suppose that you could externalize that parameter.
I think you should ask a more specific question if you want to get a better answer.