Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 718
j.doe Avatar asked Jan 28 '26 06:01

j.doe


1 Answers

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.

like image 116
davidxxx Avatar answered Jan 30 '26 18:01

davidxxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!