Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
101
rated 0 times [  103] [ 2]  / answers: 1 / hits: 11163  / 11 Years ago, mon, february 10, 2014, 12:00:00

So I want to have an immutable Vector class. For this I need to have a public getter for the x and y coordinates and a private setter so that I can actually initialize those values in the constructor.



I have a few options at my disposal so I'm wondering which one is per convention.



I could do it like this:



class Vector {
constructor(private _x: number, private _y: number) { }
public get x() {
return this._x;
}

public get y() {
return this._y;
}
}


But I don't know if using an underscore is a common thing to do. This might be an issue since that name will be visible in the intellisense.



The second option could be



class Vector {
constructor(private x: number, private y: number) { }
public get X() {
return this.x;
}

public get Y() {
return this.y;
}
}


As far as I know, only classes start with capitals in JS so this might also be a bad idea.



What is the preferred way to handle this?


More From » typescript

 Answers
5

The general consensus so far has been to use the underscore. Private variables are not shown in auto-completion outside of the class - so you wouldn't see _x or _y in auto-completion on an instance of Vector. The only place you will see them is when calling the constructor and if that really offends, you can avoid auto-mapping (although I'd rather have the auto-mapping).



class Vector {
private _x: number;
private _y: number;

constructor(x: number, y: number) {
this._x = x;
this._y = y;
}

public get x() {
return this._x;
}

public get y() {
return this._y;
}
}

var vector = new Vector(1, 2);


There is no official standard on this yet - but it is best to follow JavaScript style naming conventions if there is any chance whatsoever of interacting with external code as it will avoid switching conventions back and forth depending on whether you are calling a Function We Made or a Function They Made.



Avoiding differences only in case is also a recommendation in Code Complete by Steve McConnell - which is another bad point against x and X along with the naming convention point you mentioned in the question.


[#47871] Monday, February 10, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dayanaracolleeng

Total Points: 7
Total Questions: 96
Total Answers: 104

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
;