N
nvinhphu
Hello everybody,
I have implemented a code like this, in one of my class who has a
private data member: std::String name_ ..., variables with _ mean
private data members:
void compute ( double x )
{
if ( name_ == "linearSoftening" )
{
fval_ = linearValue ( k1_, k2_, x );
fder_ = linearDerivative ( k1_, k2_, x );
}
else if ( name_ == "exponentialSoftening" )
{
fval_ = linearValue ( k1_, k2_, alpha_, x );
fder_ = linearDerivative ( k1_, k2_, alpha_, x );
}
...
}
So, everytime a new softening law, say powerSoftening, is to be added,
I have to do two things:
(1) Code the two functions powerValue (...) and powerDerivative(...)
(2) Add a else if in the above void compute (double x) method.
I think this design is not object-oriented. I am thinking of the
following design. A base class
class SofteningLaw{
double computeVal ( double x);
double computeDer ( double x);
};
class LinearSofteningLaw : public SofteningLaw
{
private:
double k1_;
double k2_;
public:
double computeVal ( double x){return k1_ + k2_ *x;}
double computeDer ( double x){return k2_;}
};
and other class for each softening law.
Then, in my class, I store a pointer to SofteningLaw as
class myClass{
private:
SofteningLaw* softening_;
double val_;
double der_;
public:
void compute ( double x ){
val_ = softening_-> computeVal (x);
der_ = softening_-> computeDer (x);
}
};
My question is there is better way to implement the same thing here?
I really appreciate your help.
Thank you very much.
Phu
I have implemented a code like this, in one of my class who has a
private data member: std::String name_ ..., variables with _ mean
private data members:
void compute ( double x )
{
if ( name_ == "linearSoftening" )
{
fval_ = linearValue ( k1_, k2_, x );
fder_ = linearDerivative ( k1_, k2_, x );
}
else if ( name_ == "exponentialSoftening" )
{
fval_ = linearValue ( k1_, k2_, alpha_, x );
fder_ = linearDerivative ( k1_, k2_, alpha_, x );
}
...
}
So, everytime a new softening law, say powerSoftening, is to be added,
I have to do two things:
(1) Code the two functions powerValue (...) and powerDerivative(...)
(2) Add a else if in the above void compute (double x) method.
I think this design is not object-oriented. I am thinking of the
following design. A base class
class SofteningLaw{
double computeVal ( double x);
double computeDer ( double x);
};
class LinearSofteningLaw : public SofteningLaw
{
private:
double k1_;
double k2_;
public:
double computeVal ( double x){return k1_ + k2_ *x;}
double computeDer ( double x){return k2_;}
};
and other class for each softening law.
Then, in my class, I store a pointer to SofteningLaw as
class myClass{
private:
SofteningLaw* softening_;
double val_;
double der_;
public:
void compute ( double x ){
val_ = softening_-> computeVal (x);
der_ = softening_-> computeDer (x);
}
};
My question is there is better way to implement the same thing here?
I really appreciate your help.
Thank you very much.
Phu