I have a Java class which represents the correlation between two elements (typical POJO):
public class Correlation { private final String a; private final String b; private double correlation; public Correlation(String a, String b) { this.a = a; this.b = b; } public double getCorrelation() { return correlation; } public void setCorrelation(double correlation) { this.correlation = correlation; } }
To follow the correct correlation logic if a equals b then the correlation value should be ALWAYS 1. I could add the logic altering the getter method (ignore the fact of the possible null value for a):
public double getCorrelation() { if (a.equals(b)) { return 1D; } else { return correlation; } }
What bothers me is adding this logic to a getter method, should I change the method name or documenting it should be considered enough?
Back in the early days of Java getter/setter pairs were used to identify properties of beans exactly for the purpose of making it possible to define conceptual attributes implemented through computation rather than a plain member variable.
Unfortunately with the passing of time programmers have come to rely more and more on getter/setters being just accessors/mutators for underlying attributes, trend that was sort of made official with the introduction of the term POJO to identify objects that only had getters and possibly setters as methods.
On the other hand it is a good thing to distinguish objects that perform computations from objects that just carry data around; I guess you should decide which type of class you wish to implement. In your place I probably would make correlation an additional constructor argument and check it's validity there, rather than in your getter. Your Correlation
cannot be a computational object, as it doesn't have enough information to perform any computation.
Side effects in getters and setters is generally not a great idea as it is usually not expected and can lead to tricky bugs. I would suggest creating a "correlate()" method or something else that is not specifically a getter in this case.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With