Search code examples
javascriptgetter-setter

Is it bad practice to create setter and getters to simplify functions in JavaScript?


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:

  • getStatus(), getRatio()
  • setUIArrayValue(key, value), setIDText(id, text)

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.


Solution

  • 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 :

    • to avoid repeating yourself.
    • to make your code more readable and straight understandable by abstracting implementation details in a function that conveys an explicit naming.

    Using this kind of function is a good thing as it provides a better quality code.