So I have a class that has the following code:
class A {
int static value = 0;
public void executeOperationforFooValue(int number) {
B b = new B();
B.executeFooValueChange(number);
}
public void setFoo(int value) {
if (A.value == 0) {
A.value = value;
} else {
A.value = A.value + value;
}
}
}
class B {
A a = new A();
public void executeFooValueChange(int number) {
setFoo(number);
}
public void setFoo(int number) {
a.setFoo(number)
}
}
where SetFoo would take a values from outside classes, and add/subtract them during the life of the current instance of A. I tried originally to use this (and not have it static), but when the B.executeFooValueChange() would finish execution and return to class A, the value for value would reset to 0.
The problem that I'm running into is when developing JUnit tests for class A. My understanding is that when I instansiate a new instance of Class A, all variables in the class scope would be set to their default values. However when I run the following code:
public final void testA() {
A a = new A();
A.executeOperationforFooValue(1);
assertEquals(1,a.setFoo();
}
public final void testB() {
A a = new A();
A.executeOperationforFooValue(2);
assertEquals(2,a.setFoo();
}
the second test will fail (the order doesn't matter), as the value of a.setFoo() is three, not the defined value. Is there a way around this issue, or is my architecture of how class A and B relate to each other is unsound?
The reasons that I returned the values set in class B to class A is that class A would need that value for further processing, and class B would have multiple operations and value returns based upon what number is submitted. I didn't have class B extend class A as when designing their relationship, I felt there was no relationship between them. In this I could be incorrect.
My understanding is that when I instansiate a new instance of Class A, all variables in the class scope would be set to their default values.
No. Only instance variables. Your value
variable in A
is a static variable. The fact that you're using it from the setFoo
method is a design smell to start with - I'd expect an instance method called setFoo
to change some state about the instance of A
on which I call it. Instead, it's changing global state.
I strongly suspect that your value
variable should be an instance variable rather than a static variable. See the Java tutorial for more about the differences between static members and instance members.
See more on this question at Stackoverflow