Note: Questions with similar title have been asked before, but please read the full text before claiming that this is a duplicate.
Since everybody in OOP uses the terms getter and setter, I would expect they have a well-defined meaning. But what I found are basically two statements that are somewhat contradictory:
(A) They provide read or write access to a specific attribute.
This is what practically all getters and setters I have seen in production code do. A getter returns the value of an attribute and a setter sets the value of one attribute.
On the other hand:
(B) They allow hiding the internal representation of data inside a class while still being able to access and modify it.
An example in Java:
private double x, y;
public double getX() { return x; }
public double getY() { return y; }
This obviously conforms with (A). Now according to (B) we could change the data representation:
private double angle, distance;
public double getX() { return distance * Math.cos(angle); }
public double getY() { return distance * Math.sin(angle); }
This no longer conforms with (A) because there are no longer attributes named X and Y and the return values are the result of a calculation. But I would still call them getters.
Some more examples:
This is obviously a setter:
private double length; public void setLength(double newLength) { length = newLength; }
Most definitions allow the setter to do some checks:
private double length; public void setLength(double newLength) { length = (newLength > 0) ? newLength : 0; }
Not sure about this one. Note that there could be multiple setters for one attribute:
private double length; public void setLengthInInches(double newLength) { length = 25.4 * newLength; }
This one sets two attributes:
private double length; private UnitType lengthUnit; public void setLengthInInches(double newLength) { length = newLength; lengthUnit = UNIT_INCH; }
Similar to 4 but with two arguments:
private double length; private UnitType lengthUnit; public void setLength(double newLength, UnitType newLengthUnit) { length = newLength; lengthUnit = newLengthUnit; }
Another variation:
private double length; private UnitType lengthUnit; public void setLength(LengthType newLength) { length = newLength.getValue(); lengthUnit = newLength.getUnit(); }
Here the attribute does not exist but can be calculated:
private double start; private double end; public void setLength(double newLength) { end = start + newLength; }
What about this one:
private int productId; private Price price; public void setLength(double newLength) { productId = getProductIdByLength(newLength); price = BASE_PRICE + PRICE_PER_LENGTH_UNIT * newLength; }
And this one:
private double length; public void setLength(SomeInput input) { length = input.doSomeComplicatedStuffToCalculateLength(); }
Which of these are setters and which are not?