Java保护字段与公共getter [英] Java protected fields vs public getters

查看:107
本文介绍了Java保护字段与公共getter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是更好的做法和原因:通过受保护字段或私有字段上的公共getter访问基类变量。

What is better practise and why: accessing base class variables through a protected field or a public getter on the private field.

(无论如何,getter将是公共的)

(The getter will be public regardless)

推荐答案

如果无论如何都会有一个公众的吸气者,你为什么要比绝对必要的更广泛地揭露这个领域呢?这意味着它可以立即由子类写入(除非它是最后的开头)。

If there's going to be a public getter anyway, why would you want to expose the field itself more widely than absolutely necessary? That means it's immediately writable by subclasses (unless it's final to start with).

我个人认为我的所有字段都是私有的:它提供了API和实现之间更清晰的分离。我认为超类和子类之间的关系类似于调用者和被调用者的关系 - 对底层实现的更改不应该破坏子类,而不应该破坏调用者。字段的名称是一个实施细节,不应影响其他类。

Personally I like all my fields to be private: it provides a cleaner separation between API and implementation. I regard the relationship between a superclass and a subclass as similar to that of a caller and callee - changes to the underlying implementation shouldn't break subclasses any more than they should break callers. The name of a field is an implementation detail which shouldn't impact other classes.

不可否认,我的观点偶尔会被视为极端......

Admittedly my view is occasionally seen as somewhat extreme...

这篇关于Java保护字段与公共getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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