Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming practice with a function

I have a function that returns an integer, however I would like to expand it to add a new param to it. With this param, however, the function would have to return an array.

  • Is it bad practice to have a function that returns either an array or an integer based on a param?
  • If so, how can I solve this?

I think it would be bad practice also to just copy-paste the entire function for 4-5 extra lines.

like image 231
luqita Avatar asked Aug 22 '11 18:08

luqita


People also ask

What is an example of a function in coding?

Every programming language lets you create blocks of code that, when called, perform tasks. Imagine a dog that does the same trick only when asked. Except you do not need dog treats to make your code perform. In programming, these code blocks are called functions.


1 Answers

If at all possible, I would call one function from within another.

function getSingle($arg)
{
    // Do whatever it is your function should do...
    return 1;
}

function getMultiple($args)
{
    $out = array();
    foreach ($args as $arg) {
        $out[] = getSingle($arg);
    }

    return $out;
}

For the function you have in mind, it might not be possible to do this, but it may be a good option.


As an extra note, as the functions are related to one another, I would write them as class methods to "group" them together.

Take Users for example; I might need a function to get a single user and another to get multiple users. It makes sense to collect these methods in a class:

class Users
{
    public function getUser($id){}

    public function getUsers(array $id = null){}
}
like image 99
adlawson Avatar answered Oct 11 '22 06:10

adlawson