JavaScript API Function Name Best Practices

65 Views Asked by At

Which one is the preferred way to increase a value in a API.

.setX(val,increase){
    if(increase) this.x += val;
    else this.x = val;
}
.increaseX(val){
    this.x += val;
}   
.incrementX(val){
    this.x += val;
}   
.addX(val){
    this.x += val;
}   
1

There are 1 best solutions below

0
On BEST ANSWER

There is not a "preferred" way to increase a value that I am aware of but a good rule of thumb is

  1. to be as true to the intent of the function in the function name as possible.

  2. To write functions that only do one thing

For instance this function:

.setX(val,increase){
    if(increase) this.x += val;
    else this.x = val;
}

Does two separate actions and would be better served by splitting into 2 separate functions setX(val) and maybe increaseXByVal(val)

Of the names you provided it appears that increaseX comes closest to the true intention of the function but is not clear what you are increasing it by or that it requires a parameter. This could be cleared up by using the name I provided but that is really a matter of preference.

The problem with addX is that it implies that you will be adding x to the supplied number and then returning that value. Instead what you are doing is really addingValueToX which leaves no confusion