Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Successive success checks

Most of you have probably bumped into a situation, where multiple things must be in check and in certain order before the application can proceed, for example in a very simple case of creating a listening socket (socket, bind, listen, accept etc.). There are at least two obvious ways (don't take this 100% verbatim):

if (1st_ok)
{
  if (2nd_ok)
  {
  ...

or

if (!1st_ok)
{
  return;
}

if (!2nd_ok)
{
  return;
}
...

Have you ever though of anything smarter, do you prefer one over the other of the above, or do you (if the language provides for it) use exceptions?

like image 992
Stockhausen Avatar asked Jan 19 '26 00:01

Stockhausen


2 Answers

I prefer the second technique. The main problem with the first one is that it increases the nesting depth of the code, which is a significant issue when you've got a substantial number of preconditions/resource-allocs to check since the business part of the function ends up deeply buried behind a wall of conditions (and frequently loops too). In the second case, you can simplify the conceptual logic to "we've got here and everything's OK", which is much easier to work with. Keeping the normal case as straight-line as possible is just easier to grok, especially when doing maintenance coding.

like image 137
Donal Fellows Avatar answered Jan 21 '26 01:01

Donal Fellows


It depends on the language - e.g. in C++ you might well use exceptions, while in C you might use one of several strategies:

  • if/else blocks
  • goto (one of the few cases where a single goto label for "exception" handling might be justified
  • use break within a do { ... } while (0) loop

Personally I don't like multiple return statements in a function - I prefer to have a common clean up block at the end of the function followed by a single return statement.

like image 45
Paul R Avatar answered Jan 20 '26 23:01

Paul R



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!