A
Andrea Crotti
Suppose I have a class like this
class Cont
{
private:
std::map<int, int> content;
bool hasMember(int idx);
int getValue(int idx);
};
Now what I'm doing now in cases like this is to make sure that every
time I call getValue I'm sure that the object is there, so I have to
call first hasMember.
In the caller I always do
if (obj.hasMember(idx))
int idx = obj.getValue(idx);
in this way I don't need to handle special cases when the thing is not
found, BUT in many cases this brings to useless computations, since
sometimes I have to scan the container twice.
Is there a better pattern in these situations which is not "return -1
if the object is not found"?
class Cont
{
private:
std::map<int, int> content;
bool hasMember(int idx);
int getValue(int idx);
};
Now what I'm doing now in cases like this is to make sure that every
time I call getValue I'm sure that the object is there, so I have to
call first hasMember.
In the caller I always do
if (obj.hasMember(idx))
int idx = obj.getValue(idx);
in this way I don't need to handle special cases when the thing is not
found, BUT in many cases this brings to useless computations, since
sometimes I have to scan the container twice.
Is there a better pattern in these situations which is not "return -1
if the object is not found"?