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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With