Java – a method that uses private members or public accessors
I realize that this may not be answered, but I'm looking for some guidance on whether to directly use public accessors in private members or class methods
For example, consider the following code (in Java, but it looks very similar in 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()); }
The printdimensions() function describes two methods to obtain the same information, [a] using a private member (this. NumRows, this. Numcols) or [b] through an accessor (this. Rows(), this cols()).
On the one hand, you may prefer to use accessors because you cannot inadvertently change the value of private member variables On the other hand, you may prefer direct access to private members, hoping that it can remove unnecessary function calls
I think my question is, is it a de facto standard or a preferred standard?
Solution
This is a style call I prefer to use accessors because the cost of IMHO function calls is small enough and irrelevant in most cases. This usage preserves data abstraction If I later want to change the way data is stored, I just need to change the accessor instead of looking for everything that touches the variable
However, I don't feel strongly about it. If I think I have good reasons, I will break the "rule"