Jump to content

  • Log In with Google      Sign In   
  • Create Account


Opinion needed: returning values without null checks everywhere


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
22 replies to this topic

#21 SeraphLance   Members   -  Reputation: 1299

Like
0Likes
Like

Posted 14 May 2014 - 08:42 AM

Maybe I'm missing something, but I don't see how this is all that bad.

 

If you want terseness (though I don't particularly like this sort of code) you can just do this:

if(value *foo = getThing(someKey))
{
  //do stuff
}

As far as I know, your only options for dealing with Hash Tables are NULL results, exception throwing, an out parameter and success return (like TryGetValue in C#'s Dictionary), and optional types.  All of them (sans exceptions, which is just ugly) are pretty much the same thing in the end.

 

I'm with frob that calling an "Exists" function first is a waste of both your time and the CPU's.  This is also sort of similar to the EAFP principle that python programmers love so much.  Take the Nike approach and "just do it".


Edited by SeraphLance, 14 May 2014 - 08:43 AM.


Sponsor:

#22 TheComet   Members   -  Reputation: 1448

Like
0Likes
Like

Posted 14 May 2014 - 09:48 AM

if(value *foo = getThing(someKey)) { //do stuff }

I can't get that to compile here... I need to declare foo outside of the if clause:

value* foo;
if(foo = getThing(someKey))
{
// do stuff
}

Or do something extremely retarded, such as:

for(value* foo = getThing(someKey);foo;foo=0)
{
    // do stuff
}

Other than that, I agree that there's no problem with checking for NULL.


YOUR_OPINION >/dev/null


#23 Aardvajk   Crossbones+   -  Reputation: 5779

Like
1Likes
Like

Posted 14 May 2014 - 12:24 PM


I can't get that to compile here...

 

Then there is something up with your compiler. Declaration inside if statement of the form:

 

if(Type *t = whatever())
{
}

 

is perfectly standard. One rational for it was for things like:

 

if(Type *t = dynamic_cast<Type*>(p))
{

    // t is only scoped where it is valid

}






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS