1

I have a $c variable that is calculated at the beginning of the request. After calculating this several nested methods use it as a part of their job. Is it better that I pass down the $c variable to every method or store it based on the request (cache it maybe?) and use the stored value in each method to get the value of $c.

  • Approach one:
$c = 'time consuming calculated value`

a($c);
b($c);
e($c);


function a($c){
// some work using $c
}


function b($c){
// some work using $c
}


function c($c){
// some work using $c
}


function d($c){
// some work using $c
}

function e($c) {
// some work
d($c)
// some other work
}


  • Approach two
$c = 'time consuming calculated value`;
cache::set('unique-key', $c);

function a(){
// some work using cache::get('unique-key');
}


function b(){
// some work using cache::get('unique-key');
}


function c(){
// some work using cache::get('unique-key');
}


function d(){
// some work using cache::get('unique-key');
}

function e() {
// some work
 d();
// some other work
}

I'm using the first approach right know to decouple the methods more (from data gathering) but unsure of what approach is better or are there any other approaches?

1
  • 1
    first approach is better because it avoids global state
    – Ewan
    Sep 19 '21 at 12:59
4

There are two opposing goals involved here

  • avoidance of arbitrary dependencies to some global state variables (which makes testing and reasoning about the code hard, especially when the code base grows)

  • avoidance of having to write a lot of cumbersome, similar code which repeats passing the same parameter over and over again.

Often, there is a compromise possible: if those functions a to f (or a few of them) can become member functions of a common class, $c can be passed into the constructor of that class and stored inside a member variable. So instead of purely global state or purely local state, $c becomes class level state (which ideally does not change any more after the object construction).

However, if it makes any sense to create a class with some of your function a to f as member functions cannot be decided by those nonsensical names a to f.

So let me debunk again a very common misconception we have seen in hundreds of questions here on this site over and over again: one does not make such decisions by only looking at the syntactical structure - what is "best" depends on the intended semantics and the context, and not mentioning any of those in the question makes it pretty impossible to tell what makes most sense in your case.

Not the answer you're looking for? Browse other questions tagged or ask your own question.