Skip to content

Instantly share code, notes, and snippets.

@enshahar
Last active December 6, 2018 00:34
Show Gist options
  • Save enshahar/be0377e4425bf5bc991681ddfafedbcf to your computer and use it in GitHub Desktop.
Save enshahar/be0377e4425bf5bc991681ddfafedbcf to your computer and use it in GitHub Desktop.
Thou shalt not introduce side-effects in Java toString()
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestSideEffectInToString {
private final class ToStringWithSideEffect {
private int value = 0;
public ToStringWithSideEffect() {
System.out.println("ToStringWithSideEffect() called");
}
public ToStringWithSideEffect(int v) {
value = v;
System.out.println(String.format("ToStringWithSideEffect(%d) called", v));
}
@Override
public String toString() {
System.out.println("ToStringWithSideEffect() called");
return String.format("ToStringWithSideEffect(v=%d)", ++value);
}
public void setValue(int v) {
value = v;
}
public int getValue() { return value; }
}
/*
* To check the effect of "side effect in toString()",
* first you run this test using normal "run" command.
* and then, you need to run this test using "debug" command,
* during which you need to watch the value of v1 and v2.
*/
@Test
public void testSideEffect() {
ToStringWithSideEffect v1 = new ToStringWithSideEffect();
ToStringWithSideEffect v2 = new ToStringWithSideEffect(10);
v1.setValue(10);
assertEquals(v1.getValue(), v2.getValue());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment