Opinion needed: returning values without null checks everywhere

Started by
21 comments, last by Aardvajk 9 years, 11 months ago

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".

Advertisement

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.

"I would try to find halo source code by bungie best fps engine ever created, u see why call of duty loses speed due to its detail." -- GettingNifty


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

}

This topic is closed to new replies.

Advertisement