Link to Team Stats project:
https://www.codecademy.com/courses/introduction-to-javascript/projects/team-stats
This project specifically asked us NOT to use setter methods. I would have preferred to practise using them, but I followed the instructions, assuming there must be a good reason for this. What I find very strange though, is the following:
In task 6 of this project, we create the addPlayer
method to add a new player object to the array storing all of our player objects (in the property _players
. This is where I think a setter (set players
) would be appropriate (just like what we used in the previous project, Meal Maker). But, with this option specifically ruled out in task 5, I pushed the new player object directly to the _players
property (as in the code below).
However, in the solution it is pushed to the getter get players
(as in my comment in the code below). Both work, but it seems very counter-intuitive to me that the solution not only bypasses using a setter but ALSO bypasses the actual āstoredā array (in the _players
property). Is this actually sound? Is it working by reference, or something similar? Unfortunately, the walk-through video doesnāt make any reference to this point.
const team = {
_players: [
{
firstName: 'Jordi',
lastName: 'Siscart',
age: 35
}, {
// etc.
}
],
get players() {
return this._players
},
addPlayer (firstName, lastName, age) {
const player = {
firstName,
lastName,
age
}
this._players.push(player) // solution: this.players.push(player)
}
};
The exact same things happens with the addGame
method to add a new game object to the array storing all of our games objects:
My code in addGame()
:
this._games.push(game)
// pushed directly to the stored array in the property _games
Suggested solution:
this.games.push(game)
// pushed to the getter get games
(I havenāt given the rest of the code for the games, as the format is the same as with the players i.e. only the identifiers change.)
For what itās worth, the following would be my preferred solution using setters. Iāve also seen that this is what @mtf suggests in this thread: https://discuss.codecademy.com/t/why-arent-the-getters-referenced-in-the-lessons/376392/2?u=jon_morris
const team = {
_players: [
{
firstName: 'Jordi',
lastName: 'Siscart',
age: 35
}, {
// etc.
}
],
get players() {
return this._players
},
set players(player) {
this._players.push(player)
},
addPlayer (firstName, lastName, age) {
const player = {
firstName,
lastName,
age
}
this.players = player
}
};
However, Iām really interested to get some expert opinion about why either of the other solutions would be preferrable - especially the suggested solution in the project hints and video, and why it actually works.