this is a very simple question. Suppose I have a class
class A
{
public:
A(int);
void setA(int);
private:
int a;
};
with implementation
A::A(int a_) : a(a_) { }
void A::setA(int a_) { a = a_; }
Let's say I want to avoid having a = 0
but I don't want to throw an exception, I just want to keep a valid object with a = 1
instead in that case (it doesn't matter why right now).
Then I can add an if statement in the constructor and in setA
to check whether the parameter is 0, and set it to 1 in that case. Conceptually, this tells me that in that case I should change the constructor, and instead of initializing a
there, I should call setA
in the constructor. In this way, the code for the check is only written once (keep in mind that this a simple situation but the validation could be more complicated in other situations).
Now, that approach involves having an extra function call in the constructor. Is it more efficient to write the validation code twice? What about if setA
were only to be used sporadically?