mardi 24 novembre 2015

Is exiting a function with an empty return statement good/bad practice?

I've seen many examples and this is getting me more than curious

The two examples are the following :

  • Having return;at the end of a void function, this is flat out ridiculous.
  • Using return;in the middle of a function to break out of it. I don't like it.

The following example might clarify the second case (the first one being obvious):

- SomeMethodThatReturnsSomethingOrNot(var param1){

    if (param1 == null){

         CallThisMethod();
         return;
    }

    CallThisOtherMethod(param1);

}

To a lot of people, this is fine and clear. To me, it is acceptable at best.

Why not simply using an if else? You avoid the need to return nothing in the middle of the code, it doesn't decrease readability, and, well, I don't know what else to say, it just looks like a better practice to me.

- SomeMethodThatReturnsSomethingOrNot(var param1){

        if (param1 == null){
             CallThisMethod();
        }else{
             CallThisOtherMethod(param1);
        }

    }

Now I'd like to emphasize the simplicity of the example here, I know somethign sexier could be made but lets just pretend its something a bit more complex than a null check, that requires the same kind of if-returninsteadof if-else technique.

So, what are everyone's thoughts?

I've been strongly against returning something when the method is either void, or when I don't actually want to return anything. If I end up in that situation, I like to rethink my architecture because it shouldn't happen.

Am I completely wrong/right or is there some discussing space here?

Aucun commentaire:

Enregistrer un commentaire