Should the return condition be specified or not?

78 Views Asked by At

These functions will give the same output, and they are both correct, but I want to know which is programmatically more appropriate?

code 1:

void inorder(node *t){
    if(t==NULL)
        return;
    else{
        inorder(t->left);
        cout<<t->data<<" ";
        inorder(t->right);
        return;
    }
}

code 2:

void inorder(node *t){
    if(t){
        inorder(t->left);
        cout<<t->data<<" ";
        inorder(t->right);
    }
}

Here node is a node of binary tree, having the structure:

struct node{
    int data;
    node *left;
    node *right;
};
2

There are 2 best solutions below

0
On

The second one looks better.

However, I'd personally prefer this:

void inorder(node * t){
    if(t==NULL)
        return;

    inorder(t->left);
    cout<<t->data<<" ";
    inorder(t->right);
}

It is explicit (that you dont intend to do anything if t is NULL) and avoids unnecessary block (and thus indentation) by removing the else. This approach also increases the readability and makes the code concise (think of bigger function and/or blocks, and removing of unnecessary elses).

I might refactor this function, making it two as:

//Use const wherever possible!

void inorder(std::ostream & out, node const * t){
    if(t==NULL)
        return;

    inorder(out, t->left);
    out<<t->data<<" ";  //write to any output stream
    inorder(out, t->right);
}

void inorder(node const * t){
    inorder(std::cout, t); //write to stdout
}

This way you can even print the tree to a file if you use the first function, as:

std::ofstream file("inorder.txt");

inorder(file, tree);

Hope that helps.

0
On

Regarding Code readbility - for this case 1st code is good

  1. If you check for NULL & return immediately you don't need to add braces for below else code, as you know it's not NULL.No need to write else explicitly.Directly use the pointer.
  2. This 1st code has less braces compared to 2nd code. There will be less nested blocks checking pointers i.e. if valid do something,again check pointers do something,etc.

Regarding data used - for this case 2nd code is good.

  1. I would say first of all, never pass a wrong input/parameter.In this case NULL.Always be sure to pass correct input.

  2. As you know now that you are never going to pass NULL, I would say check for if data is correct & proceed further to manipulation on it. if statement comes here.There can be multiple checks you might need further inside,leading to nested blocks with in.

This said,these both coding styles doesn't always apply to all codes. Depending on the logic & the need both can be used interchangeably.