Since "Object Oriented" is in your title, I thought I'd take the chance to give an example of an OO way to analyse this.
First of all we'll want to identify the object instigating the actions. "Send" is not an object, it is the name of an action, so that's not going to be our object. There are two candidates left in your code: user and message.
There are two ways to look at this.
- Messages take care of themselves.
- Users do all the actions.
The pros of 1.
- localises the functionality of dealing with messages to a specific class
The cons of 1.
- Semantically weird. Messages are generally passive.
Pros of 2.
- Semantically makes sense. People act on messages, not the other way around.
Cons of 2.
- If users are responsible for everything they do, the class will become bloated and difficult to maintain.
So, we have a conflict between avoiding bad semantics or avoiding bloating a class.
Perhaps there is a third way. What if we had an object that makes sure messages get where they're meant to go?
In the real world that's the post office.
This essentially gives us a factory pattern type class.
function PostOffice()
{
}
PostOffice.prototype.createMessage = function(messageBody)
{
this.message =
{
"body":messageBody,
"fromUser": null,
"toUser": null
};
return this;
};
PostOffice.prototype.from = function(user)
{
this.message.fromUser = user;
return this;
};
PostOffice.prototype.to = function(user)
{
this.message.toUser = user;
return this;
};
PostOffice.prototype.send = function()
{
//whatever sending means
};
var po = new PostOffice();
po.createMessage('hi').from('user1').to('user2').send();
This is obviously a toy example, but hopefully you get the idea.