Why do I need a setter, if I am using _ to not have the property changed by others?

I didn’t get my explanation from site, and I wanted to explain it well with a few explanations. I’m guessing that’s what forums are for?

7 Likes

Isn’t the point of the underscore-prefix to signal the priority to not directly reassign the variable value?

1 Like

It actually goes further in that you shouldn’t rely on/use it at all. As the underscore indicates it is intended to be private and not part of the public interface it could be changed or even removed in a future version, breaking your code if you was using it.

There are many reasons why properties are used, it comes under the core Object Oriented Programming principle of Encapsulation. If anyone wants to know about why properties are used read up about that. There are so many articles explaining the history and reasons that there should be something for everyone to understand.

2 Likes

Yes, my bad. In my example, you wouldn’t actually add an underscore before the property name

2 Likes

Yes, I recall Encapsulation. We want modularity and sufficiency by code sections. Are we more marking the _ prefix for spots where we know changes are significant to the code, to highlight and/or find them more reliably? I notice we use accessors of getting and sometimes setting as a link to the value references and making them dynamic, but I’m guessing we utilize _prefixes and accessors for these reasons in most every good practice case. Is that true?

1 Like

The underscore convention is there to indicate that something is intended to be private, but why show something is meant to be private? Because in Javascript you can’t have private members that can only be accessed by the containing object (that is technically a lie, I know) you need a way to show something should be private.

So that is why we use it. But what is the benefit of something being private?

Something being private simply means that it isn’t meant to be used outside of what it was declared on. What does this mean for something outside of the object that tries to use it? That although it is there now, or works a certain way at the moment in a future release it may do something different or not exist at all. So even though things outside the object can technically access it they shouldn’t, and if they do they can’t moan that their code is broken because something that was private is changed.

So why would you make something private? When you make a class (or prototype in the case of Js), you decide on the public interface (public members) for it, this interface is a contract, you are saying if you use this class or an object of this type you can do xyz with it. Think of it like a plug socket, it is an interface, if you make something that meets the pattern of the pins and insert into it, it will give you electricity. Lets make a type safe collection class for example (basically pseudo code):

class TypeCollection {
    constructor(type) {
      this._type = type;
      this._collection = {};
    }
    
    Add(value) {
        this._validateType(value); // method that validates the item is of the type entered in the constructor
        this._collection[_collection.legnth] = value;
    }

    // Lots of other methods and properties
    }
}

So we have a few private fields there, like backing collection, which in this case I did as an object. Now if you start to us this field in your code to directly access the backing collection and I change the code to:

class TypeCollection {
    constructor(type) {
      this._type = type; // pretend we checked this is actually a type and not something like a general function
      this._collection = [];
    }
    
    Add(value) {
        _validateType(value); // method that validates the item is of the type entered in the constructor
        this._collection.push(value);
    }

    // Lots of other methods and properties
    }
}

All your code is not broken because the backing collection is now an array. The public contract still does all the same things it said it would, you can’t even tell the code has changed but behind the scenes it obviously has. This is why private members are used, they give you the freedom to change your implementation without changing the contract of the class and breaking code.

There is a little bit of the _ prefix being used so that when you are using it in a class you know it is private - the convention also exists in languages that can have private members also, so these can’t be using it to indicate to users that it is private because they can’t even access it without knowing they are accessing a private member (reflection).

1 Like

errr. yea, so what is the point of getters and setters then? no one knows it seems

They serve a valuable role in validation, for one. Do we need them in JS? One could argue, no, but that would be very one-sided and not the best attitude going forward. Rather than question their value, why not just learn how to write and use them and let your experience down the road give you the answer you need?

A good many beginners want all the answers up front, even while they may not understand them. Be a beginner and start at the beginning… with rudiments, not theory.

3 Likes

Why use setters and getters?

Why do I need a setter, if I am using _ to not have the property changed by others?

So encapsulation. If you have issues understanding encapsulation, it’s benefits and what it allows you to do then feel free to ask a specific question and I’ll try answer.

Or is the question why use them in JavaScript if the backing field can be accessed anyway, completely avoiding the intended encapsulation? See:

Why do I need a setter, if I am using _ to not have the property changed by others?

tldr; As a developer, you care about the public interface of what you make. If someone chooses to use things you’ve indicated should be private then it is their issue if their code breaks when you make changes to those non public things. You add a public interface with encapsulation, people bypass it at their own risk.

yes second link was a bit long. but thank you for your reply.

Sorry for jumping in but thought I would make an addition…

If you did want another case then I would modify the first condition to: numLevel !== ''

therefore checking to make sure that a value does actually exist

final line for all three conditionals:

if ( numLevel !== '' && typeof numLevel === "Number" && numLevel > 0 ) { 
    etc.....

Having said that I agree that the first condition isn’t needed because you can’t check the typeof nothing, plus numLevel can’t be greater than 0 if there’s nothing there to check whether it is or not.

1 Like

It is the condition of an if statement

there is should be “number”

You are missing the console.log() on the else return.