I think, it is easier explain using an example. Let's take a class that model the speed of a Formula 1 car, the interface may look something like:
class SpeedF1
{
public:
explicit SpeedF1(double speed);
double getSpeed() const;
void setSpeed(double newSpeed);
//other stuff as unit
private:
double speed_;
};
Now, negative speed are not meaningful in this particular case and neither value greater then 500 km/h. In this case the constructor and the setSpeed function may throw exceptions if the value provide is not within a logical range.
I can introduce an extra layer of abstraction and insert a extra object instead of double. The new object will be a wrapper around the double and it will be construct and never modify. The interface of the class will be changed to:
class ReasonableSpeed
{
public:
explicit ReasonableSpeed(double speed); //may throw a logic error
double getSpeed() const;
//no setter are provide
private:
double speed_;
};
class SpeedF1
{
public:
explicit SpeedF1(const ReasonableSpeed& speed);
ReasonableSpeed getSpeed() const;
void setSpeed(const ReasonableSpeed& newSpeed);
//other stuff as unit
private:
ReasonableSpeed speed_;
};
With this design SpeedF1 cannot throw, however I need to extra pay an object constructor every time I want to reset the speed.
For class where a limited set of value are reasonable (for example the Months in a calendar) I usually make the constructor private and provide a complete set of static functions. In this case it is impossible, another possibility is implement a null object pattern but I am not sure it is superior to simply throw an exception.
Finally, my question is:
What is the best practise to solve this kind of problem?
will build– Yakov Galka Aug 27 '11 at 16:15[built](http://en.wikipedia.org/wiki/ThrustSSC) a supersonic car and will file you a bug.