Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coding style - Input validation

Which is the best way of validating an input passed to the function i.e. do you validate all input before proceeding some thing like

class A;
void fun(A* p)
{
  if(! p)
  {
    return;
  }

 B* pB = p->getB();
  if(! pB)
  {
    return;
  }

.......

}

Or do you write it like this:

void fun(A* p)
{
  if(p)
  {
    B* pB = p->getB();
    if(pB)
    {
      .....
    }
  }
}

I am asking this because, if I use the first style then I'll have multiple return statements in my code which many people say are bad (don't know why) and if I use the second style then there will be too many levels of nesting in my code.

like image 511
Naveen Avatar asked Feb 02 '26 23:02

Naveen


2 Answers

The first way is easier to read and less complex (by depth) than the second one. In the second one, the complexity and depth increase as the number of parameters goes up. But in the first example, it's just linear.

like image 96
Mark Canlas Avatar answered Feb 05 '26 11:02

Mark Canlas


Multiple returns: people and coding standards go both ways. in C++, imo there is no reason not to prefer multiple returns (and exceptions), if you are using RAII etc. Many C coding standards enforce single-entry-single-exit to make sure all cleanup code gets executed, because there is no RAII and scope-based destruction/resource cleanup.

Should a function have only one return statement?

like image 29
Dustin Getz Avatar answered Feb 05 '26 12:02

Dustin Getz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!