Best practice for returning to a PHP function / method

I am reorganizing an extensive overtime code base. In the end, we will develop the whole system in classes, but at the same time I will use the opportunity to improve my PHP skills and improve some of the obsolete codes that we use on several hundred websites.

Over time, I read controversial articles about how best to return data from a user-defined function, usually debates fall into two categories: those that relate to best technical practice, and those who are concerned about the ease of reading and presentation.

I am interested in the opinions (with clarification) about what you consider best practice when returning from a user-defined PHP function.

I do not know which of the following should be considered as the best standard for using this basic theoretical function, for example:

Approach a.

Filling the returned variable and returning it at the end of the function:

<?php function theoreticalFunction( $var ) { $return = ''; if( $something > $somethingelse ){ $return = true; }else{ $return = false; } return $return; } ?> 

Approach b.

Return at each endpoint:

 <?php function theoreticalFunction( $var ) { if( $something > $somethingelse ){ return true; }else{ return false; } } ?> 

A possible duplicate might be What is the best PHP practice for using functions that return true or false? however, this is not limited to just true or false, despite the fact that my main example is above.

I looked at the PSR guidelines but didn't see anything (but maybe I missed it, so please feel free to tell me the PSR with a link :)).

Extension of the original question:

Is the method used to return depending on the expected / desired type of output?

Does this method change depending on the use of procedural or object-oriented programming methods? As this question shows, object orientation brings its own eccentricities to further expand the possible formatting / presentation options. Recommendations on return methods in PHP

Please try to be clear in your explanations, I'm interested in WHY you choose your preferred method and what, if you like, made you choose it using a different method.

+6
source share
6 answers

There are people arguing about single exit points in functions (only one return at the end) and others who claim that they do not work / return earlier. It is simply a matter of opinion and readability / comprehensibility on an individual basis. There is hardly any objective technical answer.

The reality is that this is simply not something that can be dogmatically prescribed. Some algorithms are better expressed as A, while others work better as B.

In your particular case, none of them is "best"; Your code should be written as:

 return $something > $somethingelse; 

This, I hope, will serve as an example of the fact that there is simply no such thing as a generally accepted rule.

+2
source

I'm prone to early returns - leave the function as soon as you find out what's going on. One type of this use, if it is called a "Security Disclaimer"

Other things that I will often include include removing the final else by default:

 if ($something > $somethingelse) { return true; } return false; 

and, in fact, form conditions if (boolean) return true; else return false if (boolean) return true; else return false , can be reduced even further (if it is clearer to you) to just return ($something > $somethingelse); . Extracting a complex if clause from code like this into a useful named function can greatly facilitate the meaning of the code.

+4
source

Using approach b is more suitable for me because in approach a you wrote very few lines of code, but if there are many lines of code and many return statements, then there is a chance that I will use the wrong return type somewhere, where $ return was assigned some other place, and I did not notice this.

0
source

Option I prever b. This is not only more readable (you know for sure that you do not need to consider any of the remaining code after the return ), but it is also more secure.

If you have an error in the rest of the code or if you encounter a set of conditions that you did not consider when developing the system, it would be possible that your result would be changed. This is not possible when you exit a function using return [$someVariable] ;

0
source
 <?php function theoreticalFunction( $var ) { if( $something > $somethingelse ){ return true; } return false; } ?> 

This approach can also be used as in the RETURN statement, the program cursor is returned, and the next statement will not be executed.

0
source

I know this question is old, but it is interesting and for me there are many things to say about it.
The first thing to say is that there is no real standard for returning to functions or methods.
This is usually a rule according to the rules adopted by your team, but if you are the only one in this refactoring, you can do what you think is best.

In case of returning the value, the important thing, I think, is readability . Sometimes it's better to lose some performance for code that is more readable and maintainable.
I will try to show some examples with pluses and minuses.

Approach a

 <?php function getTariableType($var = null) { if (null === $var) { return 0; } elseif (is_string($var)) { return 1; } else { return -1; } } 

Pros:

  • Clarity. Each case explains itself, even without comment.
  • Structure. There is a branch for each case, each case is clearly delineated and it is easy to add instructions for a new case.

Minuses:

  • readability. All of these if..else brackets make the code difficult to read and we really need to pay attention to every part to understand.
  • No code required. The last else not required, and the code will be easier to read if return -1 was only the last statement of the function, outside of any else .

Approach b

 <?php function isTheVariableNull($var) { return (null === $var); } 

Pros:

  • readability. The code is easy to read and understand, at a glance we know that the function checks if the variable is null.
  • Brevity. There is only one statement, and in this case it is good and understandable.

Minuses:

  • Limit This designation is limited to really small features. Using this notation or even the ternary operator becomes more difficult to understand in more complex functions.

Approach C.1

 <?php function doingSomethingIfNotNullAndPositive($var) { if (null !== $var) { if (0 < $var) { //Doing something } else { return 0; } } else { return -1; } } 

Pros:

  • Clarity. Each case is explicit, we can restore the logic of the function when reading.

Minuses:

  • readability. When adding many if..else code is really less readable. Then the indented code looks dirty. Imagine code with six nested if .
  • The difficulty of adding code. Since logic seems complicated (even if it is not), it is difficult to add code or logic to a function.
  • A lot of logic. If you have a lot of nested if..else , perhaps because you have to create a second function. NetBeans IDE, for example, suggests you create another function that handles the logic of all of your nested blocks. A function must be atomic ; it must do only one thing. If it is too much, too much logic, it is difficult to maintain and understand. Creating another function may be a good option.

Approach C.2

This aspect aims to provide an alternative to C.1 notation.

 <?php function doingSomethingIfNotNullAndPositive($var) { if (null === $var) { return -1; } elseif (0 >= $var) { return 0; } //Doing something } 

Pros:

  • readability. This designation is very readable. It is easy to understand what result we get according to the given value.
  • Clarity. As C .1, this approach is explicit in each branch state.

Minuses:

  • The difficulty of adding logic. If the function gets a little more complicated, adding logic would be difficult because we might need to move all state branches.

Approach D

 <?php function kindOfStrlen($var) { $return = -1; if (is_string($var)) { $return = strlen($var); } return $return; } 

Pros:

  • The default value. In this structure, we see that the default value is processed from the beginning. We have logic in our function, but if we enter without In any case, we have a value.
  • Ease of adding logic. If we need to add an if branch, this is easy, and this does not change the structure of the function.

Const:

  • No variable required. In this case, the variable $return not required, we will write the same function without using it. The solution would be return -1 at the end and return strlen($var) to if, and this will not be less readable.

Conclusion

I did not list here all the possible notation, only some of them. What we can think of them is not ideal, but in some cases it seems that the approach is better than the other. For example, the is_null function will be fine with approach B.

Using an approach or another is really up to you, it is important that you choose the logic and keep it throughout your project.

0
source

Source: https://habr.com/ru/post/987263/


All Articles