I am studying for the Java Programmer SE 7 I certification exam.
I use SelfTest Kaplan (recommended by Oracle itself).
I came across the following question: (I'll leave everything in English on purpose, not to translate and end up omitting information.)
Given:
public class Pedometer { private double stride; private double[] measurements; }
Which code fragment is a method that meets good encapsulation principles?
a) public void getStride(double stride) { stride = this.stride; } b) public void getStride(double stride) { this.stride = stride; } c) public double[] getMeasurements() { return this.measurements; } d) public double[] getMeasurements() { return measurements.clone(); }
Repsondi's c option, although I found the d option quite interesting.
When I went to see the result I saw that in fact, the correct option was d .
Why?
I'm not questioning the operation of the clone()
method and not questioning that cloning an object is "better", but questioning: Why is this implementation not common?
I have worked on several Java projects and never seen a getter like this.
Eclipse, for example, does not generate getter s in this way ( ggas
).
Not even lombok
does this implementation.
Explanation of Kaplan's response:
Explanation: The following code fragment is a method that meets good encapsulation principles:
public double[] getMeasurements() { return measurements.clone(); }
In this code fragment, the accessor method uses the
clone
method to return a copy of themeasurements
field, rather than a reference to the field itself. Accessor methods should return copies of field objects. A copy of a field will prevent other classes from modifying fields directly and will require going through mutator methods.The two versions of the accessor method
getStride
do not meet good encapsulation principles. Neither method returns the value of thestride
field as expected, but instead modifies thestride
field like a mutator method. Also, the statementstride = this.stride;
overwrites thestride
parameter, rather than assigning thestride
parameter to thestride
field as expected.The accessor method
getMeasurements
that returns a direct reference to themeasurements
field object does not meet good encapsulation . Accessor methods should not return direct references to field objects. Direct access will allow other classes to modify fields directly without going through mutator methods.