Using getters and setters for objects

I wonder if its good practice to create a helper class with getters and setters to hold values, in my recent app I created some Person objects with different kind of values and stored the object array with Ionic storage. For me it seems like it works great but would like to have some more input about it.
This is my class;

export class Help {
private id:string
private title: string;
private name : string;
private email:string;
private phone:string;
constructor() {
 
}
setName(name:string){
    this.name=name;
}

 getName(){
    return this.name;
}
  setTitle(title:string){
    this.title=title;
}

 getTitle(){
    return this.title;
}
  setId(id:string){
    this.id=id;
}

 getId(){
    return this.id;
}
  setEmail(email:string){
    this.email=email;
}

 getEmail(){
    return this.email;
}
  setPhone(phone:string){
    this.phone=phone;
}

 getPhone(){
    return this.phone;
}
toString(){
    return "Jag heter "+this.name+" my title is  "+ this.title+
    " my id is "+ this.id+" my phone number is "+this.phone+
    " and my emsil is "+ this.email;
}

}

I use to write my object like this, but since it’s the major goals to spare code to have a faster boot time, I wrote them now like following:

 export class Help {
   id:string;
   title: string;
   name : string;
   email:string;
   phone:string;

  toString(): string {
      return "Jag heter "+this.name+" my title is  "+ this.title+
      " my id is "+ this.id+" my phone number is "+this.phone+
    " and my emsil is "+ this.email;
   }
}

Don’t know if it’s the best way, but it works and it save lines.

TypeScript already has set/get available for any property of a class.

class person
{
    private _name: string;

    get name(): string
    {
        return this._name;
    }
    set name(name: string)
    {
        this._name = name;
    }
}

You can then just directly set values
e.g. person.name = “John”;
but they will always be redirected through the function for processing

1 Like

When I came to JavaScript from Java, I had this same instinct. Somewhere along the way I found that it causes too much hassle (even aside from code bloat) and I wasn’t seeing enough benefit, so now I have a rule of “don’t try to put any intelligence into data objects; leave it in the services that wrangle them”. As a result, I wouldn’t even make your Person a class, I would make it an interface:

export interface Person {
  id: string;
  title: string;
  name: string;
  email: string;
  phone: string;
}

I’m not going to try to argue that mine is the One True Way here, but I’m glad I restrict my use of class to objects that are managed by DI (i.e. Angular/Ionic entities).

2 Likes

I also use interfaces to define objects, and use classes only for pages and components. My motivation is to increase object immutability, which avoids a lot of errors that are easy for me to make in Javascript, since Javascript passes so much by reference.

The other big shock I got when moving from Java to Javascript was that const no longer defines constants. At this point, I’ve adopted the following hopefully-best-practice:

To declare a variable:

  1. Always use const, unless you just can’t.
  2. Use let when you can’t use const.
  3. Never use var.

I’m pretty sure that’s reduced my debugging time, but I can’t prove it.

Interesting. I find const in JavaScript less than worthless, although 99% of that is probably the fault of my brain that has been trained on decades of C/C++.

In that world, we have const char *p, which means “you can’t modify the string that p is pointing to”. That is the concept of object immutability that you seek (and I agree, it’s a great help). We also have char * const p which means “you can’t reassign p to point at some other string, but you can use p to modify the string it’s pointing at”. That’s IMHO considerably less useful, and by that I mean I still haven’t come across a single situation where I was glad to have that feature.

Sadly, that second meaning is all we get out of JavaScript’s const. So:

const car = {model: "Lotus", color: "red"};
// won't let us do this
car = {model: "Cadillac", color: "white"};

// but no problem here
this.testDrive(car);

testDrive(c) {
  car.model = 'Pinto'; // ha ha suckers
}

So since JavaScript’s const lulls me into a false sense of security, but doesn’t actually protect against what I want to protect against, I just pretend it doesn’t exist.

1 Like

I’ve tried to train my brain that const means BASIC let. Only partly joking. I think of it as a step toward immutability. Also, using const all the time has taken away its mojo. When I just used it for pi or whatever, it was more special.

Well let is just an upgraded version of var, it’s the same.

As for the rest, using const all the time is dangerous, because you explicitly say your value will NEVER change.
And in most cases, you want a listener to work with recordings or page load.
Hence, use CONST only for a few things, then let / var for what you have in the current page / service.

(unless you don’t use Ionic 2 but some older versions).

By the way Angular lib has some built-in features for getters and setters:
https://docs.angularjs.org/api/ng/directive/ngModel

AngularFire2 too, but i forgot where i read that on the docs.

Have fun with Ionic :slight_smile:

I would not call it “the same” at all. let has much more narrowly defined scope than var does.

Didnt even think about interfaces, thank you. My app is only connecting to a json api fetching alot of data and displays it to some lists and a map. Iam also saving it to ionic storage for offline view but i really dont need to create a new helper class for holding objects. I just did it because im coming from Java and thought it would make the code more oop and easier to maintain for co workers.

That’s not what const does in Javascript. It stop the reference from changing, not the values.

Thanks for the clarification @AaronSterling, I guess I’m not clear with what is a reference and a value in traditional JavaScript.

const notReallyConstant = {color: 'red');
let uhOh = notReallyConstant;
uhOh.color = 'blue';
console.log(notReallyConstant.color); // prints blue, not red

The issue is that uhOh and notReallyConstant both point to (i,e., refer to) the same data in memory. const makes notReallyConstant point there and it can’t change where it points. But there’s no “natural” JavaScript command to protect the memory locations.

This is the tip of an iceberg. If you’re interested in this, take a look at the library immutable.js. I try to make all my objects as immutable as possible, because debuging an issue like the code above can be very difficult.

Edited to add: ES6 makes this easier. My code uses Object.assign a lot, in order to avoid anything like the red/blue code example.

Thanks a lot for taking the time to answer me @AaronSterling.
I checked one of your many suggestions today while working on data passing across pages issues, the micro-framework you suggested to store it locally, then passing to pages.
Unfortunately, because I’m in app coding and it crashed so much while trying to use in CLI “ionic emulate android” I also lost my Chrome history.

Can you remember me, what was that micro framework you use to store files or data locally please?
Thanks, François

I was talking about Ionic Storage. If that isn’t working for you, you could build a small redux service, basically a provider that keeps a global variable or global state. Or publish an Ionic event, though that seems like overkill. I use Events for “user logged out” and similar major announcements.