Why use a getter and not a method?

I don’t understand why using getters is necessary. I tested the code, and it works exactly the same if you declare energyLevel() as a regular function, and then when you log it, you just have to call it with parenthesis, like a standard function.

Codecademy provided a few reasons for using getters:

  • Getters can perform an action on the data when getting a property.
  • Getters can return different values using conditionals.
  • In a getter, we can access the properties of the calling object using this .
  • The functionality of our code is easier for other developers to understand.

The only one that seems legitimate to me is the last reason, simply that using the get keyword can help make your code aka your intention, more readable to others. But can’t you achieve the first three things on that list with a standard function?

12 Likes

Given that without a getter, all we can do is poll the attribute for its value,

instance.attribute

anything else would require a special method which we would have to invoke on the value. Not insurmountable, but will take some thought.

Using a getter, we can perform an action (some process) and/or dress up the return by containing not just the polled value, but other data associated with the attribute or value.

Again, without a getter, we would need a method to evaluate the conditional(s) and return it.

In both the above cases one can envision a couple of static class methods filling in for those roles. We need to dig for some examples, which I am hard pressed to drum up off the top of my head.

4 Likes

I see. I guess I was confused because the example provided in the exercise didn’t seem to require a getter for the desired result.

4 Likes

@mtf and @yekusiel or any one pls, I don’t see the difference btw a getter and a method. Can anyone help me understand this two thing.

1 Like

All getters are methods, but not all methods are getters. Only those specially declared with get are getters, and they always return the value of the variable to which they are associated. Their purpose is pretty well defined.

2 Likes

Hi.

You can add values to a object i.e

const myObj = {
name: ‘Magnus’
}

myObj.age = 29;

Then age will be added to the object right.

But is it possible to add a getter and a setter function from outside the object ?

2 Likes

Right. Any property that does not exist will be created and assigned the value. If the property does exist, it will take on the new value.

Not that I am aware of. Outside of the object we can add functions, but not methods.

myObj.func = x => return x ** 2;

or, the more conventional approach would be to use function so we have a scoped this object.

myObj.getName = function() {
    return `My object name is ${this.name}.`;
}
1 Like

Having done a bit of research and played around with trying to do the same thing with a standard method and a getter, the only 3 added extras I can find that a getter does are:

  1. Using the extra get keyword makes the functionality and privacy aspects of the code clearer to other developers;
  2. A getter won’t accept any arguments as parameters;
  3. A getter cannot have it’s value reassigned.

These 3 things don’t mean you can’t get the same result with a standard method, but am I right that with the first point, this ‘clarity’ is key to the privacy aspect, and the added restrictions of the second and third points help protect the properties from unwanted manipulation?

In terms of the following advantages for using getters, given in the lesson:

  • can perform actions on data when retrieving properties;
  • can return different values using conditional statements;
  • can access the properties of the calling object using this;

… all of these things can also be done with a standard method as can be shown with the following code:

// using a getter

const robot = {
  _name: '07XYSW',
  get name () {             // name () {
    if (typeof this._name === 'string' && this._name.length === 6) {
      return this._name
    } else {
      return 'Invalid Robot Name'
    }
  }  
}

console.log(robot.name)     // console.log(robot.name())

/*
Make the 2 changes in the comments to run the same code with a standard
method (i.e. remove the keyword get, and add brackets to the method call)
*/

Or have I seriously oversimplified things?.. are there more differences/advantages with a getter compared to using a standard method to do the same thing?

3 Likes

It makes for a compelling argument. We cannot create a get or set method outside of the literal definition of the object or class.

We cannot protect them, but we can let other programmers know that we only want them accessed through their respective getter and setter. It’s important to the integrity of the data. IF there is a getter, then use it. IF there is a setter, then use it. Accessing the attribute directly will be considered trespass and a corruption of the code.

I’ll take five to consider the rest…

1 Like

Just a point to raise… I would never have validation of any sort in a getter. It is not at the polling stage we would validate data, but at the creation and/or setting stage.

Exception? The instance variable may not be set, such as having an initial value of null (or default parameter of the constructor).

return this._prop === null ? "Property not set" : this._prop;

This is akin to gong wildly off in all directions opinion so just use it as fodder for thought.

In my early days of learning about ES6 getters and setters I was of the belief that setters needed getters and likely opined on the topic (right or wrong). That belief may have been clouded all this time and I’m beginning to think they don’t need them, except to run interference while a property is being set. We cannot get a property at the same time as set. I suspect ES is binding to the getter so it cannot be called until it gets a green light from the setter. Yes, I know, more rabbit hole stuff. Do take a peek at the serious documentation when you’re brave enough and do, please report back your findings.

1 Like

What is meant by this term - I haven’t come across it before?

There are two ways to access information, either discretely or by dissemination. Discretely would be through a variable. Dissemination would be through extracting from a larger body of information.

Boiled down to two terms, poll means to access a variable directly, and query means to match results to a given value (or phrase).

console.log(a + b)

The above statement’s argument is an expression that polls two variables, a and b and adds them numerically or concatenates them if they’re strings. Either way, polling is the process.

data = ['some,' 'massive', 'table']
data[2]
// table  =>  poll
data.filter(x => x === 'table')
// [table]  =>  query

When we search a larger data structure for a match, this is called a query. Notice in the polling process we did not ask for or if 'table` was in the data. We just asked for the value at index two. A query asks for a match to a value from within the data. This could mean verifying its presence, or finding its location and reporting back. The query process is built upon A == B.

I like to call it, needle and haystack.

2 Likes

Why do I need to use the get keyword for the get function? Can I not just use it like any other method?

get is not a function, in the typical sense. There are other methods to return a property value, but get itself works internally with dedicated bindings to the property.

get prop() {

}

is bound internally to,

obj = {
    _prop: value
}

Typical usage,

console.log(obj.prop)

Notice that there is no invocation. It is detected as having a defined getter, so is bound to the backing variable, and returns that value.

I don’t understand the purpose of the “get” keyword. The example seems to work the same whether you use it or not. All it affects is whether or not you have to put the “()” after the method when invoking it.

I have quite a solid example.

Often, when we start building a new application, we declare our objects in a simple way, which make sense. For example:

let person = {
    name: 'Alan',
    age: 18
}

So, someone can call person.age and get 18.

Which is not underscored, because you don’t have that need at the very moment.

Later, when you continue to develop your application, you may need to add more checking, validation, etc.

So you decided to do some validation for your age:

let person = {
    name: 'Alan',
    _age: 18,
    
    set age(newAge) {
        if (newAge < 0) {
            console.log('You should not assign a negative number to age')
        } else {
            this._age = newAge
        }
    }

    get age() {
        return this._age
    }
}

But then the caller code does not need to change. It is still person.age.

I want to ask about this:

  • Getters can return different values using conditionals.

So, when we use methods, not getters, in an object, we cannot use conditionals? Just log something to the console?

I have thought about the getter like a person, who recieve something.
So getter not just access to something, it recieve something, and to recieve something, we have to do an action with the data, and we do an action just when use conditionals, and then recieve the result depending on condition, is it rigth?

Hi everyone!

I found this video explain the usefulness of get as compared to a method: https://www.youtube.com/watch?v=bl98dm7vJt0