简体   繁体   中英

Objects vs. Static Variables for retaining function state

I have a function which processes data that comes as a sequence. Because of this, I need to know the value of certain variables from the last function call during the current function call.

My current approach to doing this is to use static variables. My function goes something like this:

bool processData(Object message){
    static int lastVar1 = -1;

    int curVar1 = message.var1;
    if (curVar1 > lastVar1){
        // Do something
    }

    lastVar1 = curVar1;
}

This is just a small sample of the code; in reality I have 10+ static variables tracking different things. My gut tells me using so many static variables probably isn't a good idea, though I have nothing to back that feeling up.

My question: Is there a better way to do this?

An alternative I've been looking into is using an object whose fields are lastVar1, lastVar2, etc. However, I'm not sure if keeping an object in memory would be more efficient than using static variables.

Your question has a taste of being purely about style and opinions, though there are aspects that are not a matter of opinion: multithreading and testing.

Consider this:

bool foo(int x) {
    static last_val = -1;
    bool result = (x == last_val);
    last_val = x;
    return result;
}

You can call this function concurrently from multiple threads but it wont do the expected. Moreover you can only test the function by asserting that it does the right thing:

   foo(1);
   assert( foo(1) );    // silenty assumes that the last call did the right thing

To setup the preconditions for the test (first line) you already have to assume that foo(1) does the right thing, which somehow defeats the purpose of testing that call in the second line.

If the methods need the current object and the previous object, simply pass both:

bool processData(const Object& message,const Object& previous_message){

    if (message.var1 > previous_message.var1){
        // Do something
        return true;
    }   
    return false;
}

Of course this just shifts the issue of keeping track of the previous message to the caller, though thats straight-forward and requires not messing around with statics:

 Object message, old_message;
 while ( get_more( message )) {
     processData(message, old_message);
     old_message = message;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM