Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getters and setters performing additional logic

Tags:

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?

like image 908
eliocs Avatar asked Oct 31 '11 14:10

eliocs


2 Answers

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.

like image 64
Nicola Musatti Avatar answered Oct 03 '22 11:10

Nicola Musatti


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.

like image 33
cjstehno Avatar answered Oct 03 '22 09:10

cjstehno