java - setter/getter 的正确命名约定

标签 java naming-conventions

在使用 OOP 范式命名方法时,是否仅在返回成员变量时才在方法前加上“get”前缀?或者将“get”添加到名称中是否适合 OOP,即使它返回的是根据成员变量计算的值,而不是它自身的成员变量?

例如,这应该是正确的:

private int count = 0;    
public int getCount() {
    return count;
}

这会违反命名约定吗:

public int getCountPlusOne() {
    return count + 1;
}

对不起,我是一个完美主义者。

最佳答案

would it be OOP appropriate to add "get" into the name even if it is returns a value calculated from a member variable, but not the member variable it self?

Java 中 getter 和 setter 的命名不受任何“OOP 原则”的约束——它纯粹是 JavaBeans convention :

The class properties must be accessible using get, set, is (used for boolean properties instead of get), and other methods (so-called accessor methods and mutator methods) according to a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters can have one or more than one argument.

请注意约定如何故意将通过 getter 和 setter 访问的值称为“属性”,以将它们与字段区分开来。这背后的意图是涵盖计算和存储的属性。

这引出了您问题的答案:为计算属性的 getter 使用“get”前缀是完全合适的。

关于java - setter/getter 的正确命名约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19504210/

相关文章:

java - 如何在 spring config 中手动连接 hibernate session 工厂

emacs - 函数名称中的双减号 (--) 约定在 Emacs Lisp 中意味着什么

c# - 这个测试名称是不是有点过头了

c# - bool 属性命名

java - 如何在 Java 应用程序中播放 ALAW 文件?

java - 如何获取绑定(bind)到 HBM 列的属性的名称?

java将字符串中的double值解析为文字值

java - 使用 Jackson 和 Spring 将 JavaScript 数组反序列化为 Java LinkedHashSet 不会删除重复项

c# - 不同命名空间中的相同类名

oop - Web 服务中 DTO 的命名约定是什么