我意识到这可能无法回答,但我正在寻找是否有关于是否直接使用私有成员或类方法中的公共访问器的某种指导.
例如,考虑以下代码(在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());
}
printDimensions()函数说明了两种获取相同信息的方法,[A]使用私有成员(this.numRows,this.numCols)或[B]通过访问器(this.rows(),this.cols()).
一方面,您可能更喜欢使用访问器,因为您无法无意中更改私有成员变量的值.另一方面,您可能更喜欢直接访问私有成员,希望它可以删除不必要的函数调用.
我想我的问题是,要么是事实上的标准还是首选标准?