how to call a function in Python in another function?

Which is the better practice of applying conditions to call a function: before the function call or inside the function?

  • Let's say there is a function that receives a certain number of variables. If those variables are not ready, the task should not be performed. Which is better? doSomeTask( $a, $b, $c, $d ); function doSomeTask( $a, $b, $c, $d ) { if ( ! ( $a && $b && $c && $d ) ) { return; } // do something with $a, $b, $c, and $d. } if ( $a && $b && $c && $d ) { doSomeTask( $a, $b, $c, $d ); } function doSomeTask( $a, $b, $c, $d ) { // do something with $a, $b, $c, and $d. }

  • Answer:

    It likely makes more sense inside the function since if you later call the function from other places, you'd start repeating the if check. Inside: function foo(a) { if (!a) { return; } bar; } foo(a); foo(a); Outside: function foo(a) { bar; } if (a) { foo(a); } … if (a) { foo(a); }

Omer Zach at Quora Visit the source

Was this solution helpful to you?

Other answers

Use types to force this to fail at compile time.

Toby Thain

It generally makes sense to have the conditions inside the function, like your first example. BUT, you should probably throw an exception instead of just silently returning. For example: function addTwoNumbers( $a, $b ) { if ( ! ( is_numeric($a) || is_numeric($b) ) ) { throw new Exception('One or more of the parameters is not numeric'); } return $a + $b; }

Chaim Peck

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.