mercredi 17 juin 2015

Javascript programming structure

This is for you pattern and functional programming gurus: Suppose I want to write a javascript authentication api.

Here are a couple of ways I could write this:

  1. Make an object like this: mycompany.authentication (represents my package)

and put objects and functions off of it like this:

mycompany.authentication.authenticate = function(username, password) { // do authentication and populate the mycompany.authentication.user object }

and

mycompany.authentication.user = { // all of the authenticated user properties are here i.e. user.firstName }

Again, in this example the authenticate function populates the user object, and I suppose we could add another function like 'isLoggedIn()' to see if we can read the object.

OR

  1. Try to use a more object oriented (looking) approach like this:

Create a function called mycompany.authentication.UserService

where the code looks like var user = mycompany.authentication.UserService.authenticate(username, password);

and create a function like:

mycompany.User where I spell out each property of a User.

In example 1 all of the information is attached to the mycompany.authentication namespace, but in the 2nd example the User object is separate from the mycompany.authentication object.

To repeatedly get a user I'd have to ask the UserService for it like this:

if (mycompany.authentication.UserService.isLoggedIn()) { var user = mycompany.authentication.UserService.getUser(); }

Is one better than the other? Is there a better approach to this? I'm an old java developer and #2 seems like I would do it in the java world. I'm getting a little hung up on the capitalization in #2 vs. the lower-casing of the objects in #1. But mostly I've been reading about a functional programming style vs an object oriented one, and I'm leery about adding a mycompany.authentication.UserService.getUser() call to get a User object vs just referencing mycompany.authentication.user directly.

Aucun commentaire:

Enregistrer un commentaire