【问题标题】:Should Constructor Parameter Names be Abbreviations of Instance Variables?构造函数参数名称应该是实例变量的缩写吗?
【发布时间】:2019-03-10 09:44:18
【问题描述】:

例如,对于这个类,

class Dog {
    String name;
    int colour;
}

最好有一个构造函数,其参数与它们所代表的实例变量同名,如下所示:

    public Dog(String name, int colour) {
        this.name = name;
        this.colour = colour;
    }

或者最好是缩写参数的名称,像这样:

    public Dog(String n, int col) {
        name = n;
        colour = col;
    }

【问题讨论】:

  • 随你喜欢。而且,如果您关心其他开发人员能够轻松阅读您的代码,您应该使用富有表现力的名称。

标签: oop parameters constructor


【解决方案1】:

参数最好使用完整的字段名,因为这样更清楚。

即使需要稍微多一点的代码(添加 this.),清晰也能胜出。

同时避免了两个字段首字母相同时的命名约定问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    • 2010-12-31
    • 2014-01-12
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    相关资源
    最近更新 更多