Javascript Naming Convention: value() vs getValue()

javascript, naming-conventions

Solution

There's no "correct" naming in JavaScript. However, there are three conventions that are mostly used:

Independent getter and setter:

In this approach, we create both a getter and a setter functions, like in Java:

var value;

this.getValue = function () {
    return value;
}

this.setValue(val) {
    value = val;
}

Combined getter/setter method

In this approach, you have a single method that does both. The magic here is that it checks whether you provides a new value for your property:

var _value;

this.value = function (val) {
    if (arguments.length > 0) {
        // Acts like a setter
        _value = value;
        return this;
    }
    return _value;
}

It's also common to define your setter to return the actual instance of your class, so you can do this:

myObj
     .setProp1("foo")
     .setProp2("bar");

Object.defineProperty

This one is less used, but it's also an option. It's similar to Objective-C `@property` statement:

var _value;
Object.defineProperty(this, "value", {
    get: function() {
        return _value;
    },
    set: function(val) { 
        _value = val;
    }
});

Then you can access it like if it was a public property:

console.log(myObj.value);  // Calls the getter method
myObj.value = newValue;    // Calls the setter method

Problem

Imagine a simple object: ``` function createObj(someValue) { return { someFunction: function () { return someValue; } }; }; ``` It basically does: ``` var obj = createObj("something"); var result = obj.someFunction(); // "something" ``` Now, `someFunction` refers to a function that returns a value. What should be the correct naming convention used in javascript for the `someFunction` function? Should it be named as what it does? Or its ok to name it with the name of the object that it returns? I mean, should I name it `value()`, or should I name it `getValue()`? Why? Thanks in advance.

Original source

Related problems