Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
282 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...