Amplify91
Amplify91

Reputation: 2660

How to detect if a variable has changed?

I have found myself wanting to do certain things in my programs only if a variable has changed. I have so far been doing something like this:

int x = 1;
int initialx = x;

...//code that may or may not change the value of x

if (x!=initialx){
    doOneTimeTaskIfVariableHasChanged();
    initialx = x; //reset initialx for future change tests
}  

Is there a better/simpler way of doing this?

Upvotes: 10

Views: 41001

Answers (6)

Santiago Perez
Santiago Perez

Reputation: 51

Example:

create a variable with the same name with a number.

int var1;
int var2;

if(var1 != var2)
{
//do the code here

var2 = var1;
}

hope this help.

Upvotes: 4

secmask
secmask

Reputation: 8107

another way is use AOP to intercept changing of fields, AspectJ for example, you could have a look a http://www.eclipse.org/aspectj/doc/released/progguide/semantics-pointcuts.html

Upvotes: 4

jeverest
jeverest

Reputation: 44

Assuming you have multiple threads you could create an object monitor and wait for the changed object to wake all blocked threads.

Something like this:

private MyObject myObject;

... other thread ...
while(true) {
  myObject.wait()
  logic you want to run when notified.
}
... other thread ...

... later on ...

myObject.change();
myObject.notifyAll();

Upvotes: 0

james_bond
james_bond

Reputation: 6908

Since you want to find and perform some action only if the value changes, I would go with setXXX, for example:

public class X
{
    private int x = 1;

    //some other code here

    public void setX(int proposedValueForX)
    {
       if(proposedValueForX != x)
       {
           doOneTimeTaskIfVariableHasChanged();
           x = proposedValueForX;
       }
    }
}

Upvotes: 9

developer
developer

Reputation: 9478

you can also use flag concept, as when ever changing the value of x . assign true for an boolean variable. Keep boolean with default value as false. check by this way.

This way is better than having getters and setters in base of performance, not to have reduntant code of two methods getters and setters.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240870

You can use getter/setter with dirty bit associated with each field. mark it dirty if the value is changed through setter, and force user to use setters

Upvotes: 4

Related Questions