Let’s imagine the situation when your class is responsible for complicated calculations and data for processing are delivered as List collection in the constructor. During the execution of the module on the test environment, you are receiving strange results despite the same data provide you correct results at JUnit tests.
public class SomeClass {
private List<RawData> data;
public SomeClass(List<RawData> data) {
...
You made double-check and the algorithm is fine. So what can be wrong?
Let’s check how data are passed to your class in constructor.
public SomeClass(List<RawData> data) {
this.data = data;
}
...
in main method
List<RawData> data = new ArrayList();
...
SomeData someData = new SomeData(data);
You pass a mutable object (ArrayList) to your class as a reference. What does mean? It means the list can be modified at any point in time, even during the execution of your calculations. In result list in your object can change during runtime.
How to prevent that? Each time your class stores mutable members, it shouldn’t do directly. Otherwise you vulnerable to unexpected changes in your class state. To avoid that, store or return the copy instead.
public SomeClass(List<RawData> data) {
this.data = ...copy of data;
}
More you can find at MITRE CWE-374 & Clean Code: A Handbook of Agile Software Craftsmanship