Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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();
share|improve this answer
    
This answered my question, thanks. –  ahjmorton Apr 4 '13 at 20:18

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.