When I code stuff, I try to divide all things in functions (methods, if you like). Function X does stuff X, Y does tuff Y and not like method X does stuff X, Y & Z! This gives me more re-usable code. I like that. 🙂
Lets take a look on this code:
var user = {
users: [],
userCount: 0,
addUser: function(user) {
(this.users).push(user);
},
incrementCount: function() {
++this.userCount;
}
}
var user = { // 2nd example.
users: [],
userCount: 0,
addUser: function(user) {
(this.users).push(user);
++this.userCount;
}
}
(It’s in JavaScript, but language here is non-essential.)
In my opinion, second example will be easier and safer to use for, lets say, API user.
It’s easy to forget to call user.incrementCount(). What do you think? Second example does it automatically.
So how to find a balance? Any best-practices about calling functions inside of functions?
Thanks for reading this.
Edit:
This came in my mind just now:
var user = {
users: [],
userCount: 0,
addUser: function(user) {
(this.users).push(user);
this.incrementCount();
},
incrementCount: function() {
++this.userCount;
}
}
It’s a little different in JS, since there isn’t a way to make functions truly private when using object literal notation, but…
It’s all about the API you want your objects to expose to their consumers. Do you want consumers of your API to be able to increment the count separately from adding a user? If so:
Otherwise:
In this particular case, I would strongly recommend against storing any separate count at all, since the
usersarray already does that for you.