Refactoring Tip: Move Functions into Objects
December 16th, 2008
On the last project that I worked on, we were spending a lot of time learning and the code started to get out of control. Towards the end, I made a few passes through and started moving stuff around. Take the following two functions for example.
function addChat(name, room_jid, person_jid) {
// add chat stuff
}
function showChat(room) {
// show chat stuff
}
There is nothing wrong with the functions above but you can see the similarities. Both have chat in the name and both are operating on chat based stuff. What I did on the project is move them into a simple Chat object like this.
var Chat = {
add: function(name, room_jid, person_jid) {
// add chat stuff
},
show: function(room) {
// show chat stuff
}
}
Now I don’t have to remember whether I named the function addChat or chatAdd. It is much easier to remember that we have a Chat object and that it has add and show methods. I’m obviously not going to have an Add object with a chat method. Catch my drift? I think this is one of the reasons I got so frustrated with PHP back in the day. The function names were a pain to remember and the parameter order was even worse.
Moving things to an object like this makes them easier to remember and allows your code to grow. If, for example, I wanted to keep track of the current chat with a variable or the number of active chats, I could simply add those to the Chat object. Using functions, your only option would be to have a global variable of sorts, and trust me, those lead to the path of ruin. :)
If you enjoyed this post, get free updates by email or RSS.
Thanks, nice and easy tip for a Javascript noob like me! OO FTW :)
Thanks John, perfect timing - I was just thinking about this tonight.