是否总是使用get和set方法来访问类自己的成员字段? [英] Is it in an anti-pattern to always use get and set methods to access a class's own member fields?

查看:161
本文介绍了是否总是使用get和set方法来访问类自己的成员字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java课程中,使用getter和setter访问成员字段是不是一种好或坏的做法?

In Java classes is it considered good or bad practice to access member fields with their getters and setters?

例如哪个更好:

public Order {
    private Agreement agreement;

    public Agreement getAgreement() {
    return agreement;
    } 

    public void process() {
       //should I use:
       getAgreement().doSomething();
       //Or:
       agreement.doSomething();
    }
}

一般来说,我认为直接访问该字段是最好的对于KISS原则,有人可能会在以后使用不可预测的结果覆盖get方法。

In general I think accessing the field directly is best due to the KISS principle and also someone may override the get method later with unpredictable results.

然而,我的同事们认为最好保留一层抽象。对此有何共识?

However my colleagues argue that it is better to keep a layer of abstraction. Is there any consensus on this?

推荐答案

这里的核心问题是直接字段访问不适合通过子类重写方法,AOP,动态代理等进行拦截。根据具体情况,这可能是好事也可能是坏事。我会说在内部使用getter和setter不是反模式或模式。根据情况和班级设计,这是好事还是坏事。

The core issue here is that direct field access is ineligible for interception by subclass overridden methods, AOP, dynamic proxies and the like. This can be a good or bad thing depending on the case. I would say that using getters and setters internally is not an anti-pattern or a pattern. It is a good or bad thing depending on the situation, and the design of your class.

这篇关于是否总是使用get和set方法来访问类自己的成员字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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