![]() |
Question about 'return' statement in UDF...
I'm having trouble understanding a concept...(nothing new about that...) Here it is:
Here is UDF#1: function udf_1($number) { $newnumber = ($number + 100); return $newnumber ; } Here is UDF#2: function udf_2($number) { return $number + 100 ; } My question is, why would it ever be beneficial to use udf_1() over the more simple udf_2()? Thanks! Dave |
When your using longer functions with longer mathematical equations or longer bits of code then it becomes easier to read.
|
the first one also is more elaborated and more easy to understand..while the second one is quite a shortcut method in returning a variable..:P
simplified one is more easy to read and debug..:D |
As the others have mentioned, it is easier to read when it becomes more complex. Take the following for instance:
php Code:
Although this may seem nicer because it is shorter, we also run into readability issues. As a programmer you should be aware of the amount of memory used for your applications, but not paranoid. If it reads nicer, and also easier to debug, by utilising a couple more variables then I would say take that approach. We could thus refactor the above to something like the following: php Code:
Now you may think that's quite wasteful. However, in the first instance we are assuming everything will be fine and dandy, but being programmers, we know it's never that simple, and so now we've broken it up, we can add some conditional statements to check if everything really is fine and dandy: php Code:
Additionally, if you show let PHP notify you of every little thing, you will see that PHP do not recommend encasing functions within functions, as in our first example. |
best agree with that example..:D
|
Ach! Not necessarily. Challenge me :-( !
|
Quote:
|
Personally I would go off solution two, but thats many because I read both examples the same and I don't see a reason to assign alot of variables in favour of readability =)
|
Quote:
Quote:
PHP Code:
Quote:
|
The whole reason I took the prolix approach was to make a point. There are a million and one ways to find the file's extension. You're right though, your code is simpler to read, and would have been the next step in refactoring if you were to continue to find better approaches.
|
Pushing aside the issue of which return style to use - I always thought functions were to output nothing as in not display any information to the user.
|
Functions can be used pretty much anywhere where code would otherwise be repeated. In the case of this thread, such a function would be somewhat pointless, but for the extension code in my example, you would most certainly add that into a function. Whether it echoes its output or not is entirely up to you.
|
| All times are GMT. The time now is 09:26 PM. |
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0