Return policy

Share this topic:



Link to this posting

Postby Ursego » 19 Feb 2013, 22:18

Functions must return values using RETURN statement only when that makes sense.

A function is allowed to return a value using return statement only if at least one of the following conditions is true:

1. The main purpose of the function is to obtain the value, and there is only one value to return.

2. The main purpose of the function is to perform some action, but the returned value is important for the calling script (not for error processing - there are exceptions for that!), and there is only one value to return - for example, the main purpose of uf_retrieve() is to retrieve data from the database, but, in addition, it returns the number of retrieved rows so the calling script is more efficient because it doesn't need to call RowCount().

A function must NOT return a value using return statement (i.e. "(none)" must be selected as the returned type in the function's signature) if at least one of the following conditions is true:

1. The function's purpose is to perform some action, and there is nothing useful to return to the calling script.

2. The function (of any purpose) must return more than one value - they all (!!!) must be returned using ref (out) arguments. It is considered a very bad programming style if both the mechanisms are used - return statement AND by-reference arguments!

You can ask: what is the problem to have meaningless, but harmless return 1 at the bottom of the script? Nothing catastrophic, but the return value is a part of the function's contract with the outer world. Each detail of that contract is important and must have sense! Looking at the function's interface, developers make conclusions about its functionality, so if a value is returned, that has a reason and the returned value should be somehow processed in the calling script... You know, it's like adding to a function of one extra argument of type int which is not used inside, and always passing 1 through it - that argument will be harmless and not catastrophic too, but needless and foolish in the same way as the discussed return 1.
User avatar
Ursego
Site Admin
 
Posts: 112
Joined: 19 Feb 2013, 20:33

Return to Elegant Code

Who is online

Users browsing this forum: No registered users and 1 guest


Return policy

Share this topic:


If you think that this site is not too bad, please LIKE it in Facebook. Thanks!





cron
free counters

eXTReMe Tracker