Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using static function variable vs class variable to store some state

Lets say I have function like this:

void processElement() {
    doSomething(someArray[lastProcessedElement + 1]);
}

The thing is, every time this function called, I need to the store the last element that I called doSomething on. So in here I have two choices:

  • I can create a private class variable named lastProcessedElement and increment it's value every time that function is called. This approach seems most common. So the code can be something like this:

    class Foo {
        int lastProcessedElement = 0;     
    
        public:  
        void processElement() {
            doSomething(someArray[++lastProcessedElement]);
        }
    }
    
  • As second option, I can create a static variable in function and increment it every time:

    // Class is not important here, so the function is:
    void processElement() {
        static int lastProcessedElement = 0;
        doSomething(someArray[++lastProcessedElement]);
    }
    

The first solution adds a little bit complexity which I don't want. I like to keep things in-place.

I know the second solution only works if that class have only one instance.

So using static variable method is a good solution? And is there any in-line solution to multi-instance class? (There can be a solution to this particular array element index thing, but I just made that up, I'm talking about storing some value for the next call of the function)

like image 706
isamert Avatar asked Jul 13 '16 13:07

isamert


1 Answers

You already figured out why the function-scoped static is a bad idea:

only works if that class have only one instance

That's a bad design limitation.

Just keep the state as a regular class member variable.

like image 196
John Zwinck Avatar answered Nov 14 '22 21:11

John Zwinck