使用私有成员或公共访问者的方法

jed*_*rds 7 java coding-style

我大概知道这个不能回答,但是我正在寻找是否有某种是否直接使用私有成员的指导或类方法中的公共访问器.

例如,考虑以下代码(在Java中,但在C++中看起来非常相似):

public class Matrix {

    // Private Members
    private int[][] e;
    private int numRows;
    private int numCols;

    // Accessors
    public int rows(){ return this.numRows; }
    public int cols(){ return this.numCols; }

    // Class Methods
    // ...
    public void printDimensions()
    {
        // [A] Using private members
        System.out.format("Matrix[%d*%d]\n", this.numRows, this.numCols);


        // [B] Using accessors
        System.out.format("Matrix[%d*%d]\n", this.rows(), this.cols());
    }
Run Code Online (Sandbox Code Playgroud)

printDimensions()函数说明了两种获取相同信息的方法,[A]使用私有成员(this.numRows, this.numCols)或[B]通过访问者(this.rows(), this.cols()).

一方面,您可能更喜欢使用访问器,因为您无法无意中更改私有成员变量的值.另一方面,您可能更喜欢直接访问私有成员,希望它可以删除不必要的函数调用.

我想我的问题是,要么是事实上的标准还是首选标准?

the*_*ber 8

这是一种风格调用.我更喜欢使用访问器,因为IMHO函数调用开销足够小,在大多数情况下无关紧要,这种用法保留了数据抽象.如果我后来想要改变数据的存储方式,我只需要更改访问器,而不是寻找触及变量的所有地方.

不过,我对此并不感到强烈,如果我认为我有充分的理由,我会打破这个"规则".