Consider the following piece of code
class Foo
{
public:
//...
bool valueFirstGet(int& value) const
{
if(this==nullptr)
{return 0;}
value=values[0];
return 1;
}
//...
private:
int* values;
size_t n_values;
};
int main()
{
Foo* obj=findObject("key");
int value;
if(!obj->valueFirstGet(value))
{printf("key does not exist\n");}
return 0;
}
findObject returns nullptr if it cannot find the object. Is it ok to let the member function do the null check instead of its caller. In my code, there are several calls to findObject directly followed by a call to valueFirstGet so leaving the check to the caller makes the code ugly.
EDIT:
Is there a cleaner way to avoid all null checking besides having findObject to throw an exception instead of returning null?
EDIT 2:
What about a static wrapper?
valueFirstGet
on a null pointer is undefined behaviorhasObject(String): bool
method or atryFindObject(String, out Foo*): bool
. Null pointers are an error condition, not a valid return result.Maybe
orOption
type I think your best bet is something liketryFindObject
orhasObject
. Nulls are harmful, avoid if possible.