user5538720
user5538720

Reputation: 93

OOP- function inside function or one function return value for the other function (simple example inside)

I have 2 code's examples for 1

1)- In the first example- first fuction returns the result and pass it to the second fuction.

$goods_id = $_POST['goods_id'];
$goods_category = $this->getCategory($goods_id);
$goods_list = $this->getGoodsList($goods_category);

function getCategory($goods_id){
    ...
    return $goods_category;
}

function getGoodsList($goods_category){
    ...
    return $goods_list;
}

2)- In the second example- the first fuction uses the second function to get the value and then returns the result.

$goods_id = $_POST['goods_id'];
$goods_list = $this->getGoodsList($goods_id);

function getGoodsList($goods_id){
    ...
    $goods_category = $this->getCategory($goods_id);
    ...
    return $goods_list;
}

function getCategory($goods_id){
    ...
    return $goods_category;
}

What code example i should use ($goods_category won't be used anywhere else)?

Upvotes: 0

Views: 40

Answers (1)

Alexey
Alexey

Reputation: 3484

Before answering this you should complete the following prerequisites:

  1. Post here the class(es) name(s), properties, methods signatures
  2. Are ::getGoodsList() and ::getCategory($goods_id) methods of the same class or not?
  3. Please use private/protected/private method visibility keywords even if you consider them both public
  4. The two main questions: 1. whether ::getCategory($goods_id) method will ever be used somewhere outside the class visibility scope. 2. whether you need the item category below in the code once more. Answering 4.1 as "no" would yield 4.2 "no" as well.

If 4.1. is "yes" and 4.2. "yes", then declare ::getCategory($goods_id) as public and use your option #1. I.e. assign the category to $goods_category and use it anywhere below.

If 4.1. is "yes" and 4.2. "no", then declare ::getCategory($goods_id) as public and you can rewrite your code to something like

$goods_list = $class->getGoodsList($class->getCategory($goods_id));

Note that one should avoid >3-4 nested method calls. 2 is probably fine (my taste), but more than 5 in one line will make the line long and unreadable. However, it all depends on the app logic and memory usage and other stuff, so not a generic recommendation.

If 4.1. is "no" and 4.2. is "no", then declare it as protected or private if you don't plan to extend the class or you don't need the method in classes-descendants and use your approach #2:

class Util {
    public function getGoodsList($goods_id) {
        ...
        $goods_category = $this->getCategory($goods_id);
        ...
        return $goods_list;
    }

    protected function getCategory($goods_id) {
        ...
        return $goods_category;
    }
}

Upvotes: 1

Related Questions