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
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:
- How to call a popup from a link inside another popup?Best solution by stackoverflow.com
- How to call a function with parameter in a bash script?Best solution by tldp.org
- How to call functions inside a function in Python?Best solution by Stack Overflow
- How to call a function asynchronously in PHP?Best solution by Stack Overflow
- Which of the following is NOT a function of proteins?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
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.