I am writing a node.js application which I am breaking down into modules, the issue is I am not sure how to organise my code in an idiomatic Javascript way.
Currently each of my modules exposes a set of functions that are intended to be called directly. All state is modified by the module with the gameId being the first parameter :
//snip
var gameId = gameModule.createGame();
// Return the gameId down to a remote client
client.send(gameId);
}
// When a remote client wants to add a player
gameModule.addPlayer(gameId, "Player 1");
}
An alternative approach would be to actually use objects e.g. :
//snip
var game = new gameModule.Game();
// Return the gameId down to a remote client
client.send(game.getId());
}
//snip
// When a remote client wants to add a player
var gameToModify = gameModule.getGame(gameId);
gameToModify.addPlayer("Player 1");
gameModule.saveGame(gameToModify);
My question is to any Javascript programmers (or regular ones) is which of the two above alternatives looks easiest to work with / most natural?
The problem with the first code is that by hiding the Game object you prevent all direct actions on this object, as each of them involve to use the gameId
to look, inside the library, for the object. This will have an impact of performances if you do small actions. And you might be tempted to write too much code to avoid those too small actions.
Without hesitation, in your specific case, the second version is cleaner.
I would, by the way, complete the logic by enabling
gameToModify.save();
0