getter和setter执行额外的逻辑 [英] getters and setters performing additional logic

查看:95
本文介绍了getter和setter执行额外的逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java类,它代表两个元素之间的相关性(典型的POJO):

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;
    }

}

如果要遵循正确的关联逻辑a等于b然后相关值应该总是1.
我可以添加改变getter方法的逻辑(忽略a的可能空值的事实):

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;
    }
}

困扰我的是将此逻辑添加到getter方法,我应该更改方法名称还是记录它应该被认为是足够的?

What bothers me is adding this logic to a getter method, should I change the method name or documenting it should be considered enough?

推荐答案

早在Java getter / setter的早期对用于识别 beans 属性,正是为了能够定义通过计算而不是普通成员变量实现的概念属性。

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.

不幸的是,随着时间的推移,程序员越来越多地依赖getter / setter作为基础属性的访问者/变异者,这种趋势在引入术语时已成为正式em> POJO 用于识别仅具有getter和可能的setter作为方法的对象。

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.

另一方面,区分执行计算的对象是一件好事来自只携带数据的物体;我想你应该决定你想要实现哪种类型的课程。在你的位置,我可能会将相关性作为一个额外的构造函数参数,并在那里检查它的有效性,而不是在你的getter中。您的 Correlation 不能是计算对象,因为它没有足够的信息来执行任何计算。

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.

这篇关于getter和setter执行额外的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆