Example:
I'm working on a user interface for a robotics project that displays the wheel calibration ratio. The default ratio is 0.89 and I have a button that increments the ratio by 0.01.
function incrementRatio() {
if (getStatus() != "Connected" || getRatio() >= 1.00) {
stopEvent();
} else {
var newRatio = getRatio() + 0.01;
setUIArrayValue("currentRatio", newRatio);
setIDText('ratiovalue', getRatio().toFixed(2));
}
}
The function above uses getters and setters such as:
Some of these contain one statement but are frequently re-used throughout the code.
For instance, setIDText()
:
function setIDText(id, text) {
document.getElementById(id).innerHTML = text;
}
Contains 1 statement, but provides a much shorter and readable way of mutating text. Without these setters and getters, functions such as incrementRatio() would look fairly cluttered.
What you name getters and setters are not really as these perform real logic as for example the setIDText()
function :
function setIDText(id, text) {
document.getElementById(id).innerHTML = text;
}
These are rather helper/logic methods that allows both :
Using this kind of function is a good thing as it provides a better quality code.