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: 2198

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.


#22 TheComet   Crossbones+   -  Reputation: 2461

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.


"Windows 10 doesn't only include spyware, it is designed as spyware" -- Gaius Publius, The Big Picture RT Interview

"[...] we will access, disclose and preserve personal data, including your content (such as the content of your emails, other private communications or files in private folders), when we have a good faith belief that doing so is necessary" -- Windows 10 Privacy Statement


#23 Aardvajk   Crossbones+   -  Reputation: 11176

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