java - Methods using private members or public accessors -
i realize cannot answered, i'm looking whether there sort of guidance whether use private members directly or public accessors inside class methods.
for example, consider following code (in java, 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 illustrates 2 ways same information, [a] using private members (this.numrows, this.numcols
) or [b] via accessors (this.rows(), this.cols()
).
on 1 hand, may prefer using accessors since there no way inadvertently change value of private member variables. on other, may prefer accessing private members directly in hopes remove unnecessary function call.
i guess question is, either de-facto standard or preferred?
it's style call. prefer use accessors, because imho function call overhead small enough in cases doesn't matter, , usage preserves data abstraction. if later want change way data stored, need change accessors, instead of hunting places touched variables.
i don't feel it, though, , break "rule" if thought had reason to.
Comments
Post a Comment