Suppose we program in
Javascript. There is a function
updatePost that takes a boolean parameter indicating whether it should highlight the updated post or not.
updatePost: function(highlight) {
// ...code to update post...
if (highlight) {
post.highlight()
}
}
One would definitely call it like this:
this.updatePost(true);
The problem is, that's not very explanatory. In other words, you can't tell straight from the line what this
true does.
I propose a solution that takes advantage of
loose typing: just pass a string containing a parameter meaning as an argument.
this.updatePost('and highlight');
Now, this is definitily more verbose.
2 комментария:
That's a great idea; it's also useful with enumerated values like 'before'/'after'.
Another technique is
updatePost: function (options) {
// ...code to update post...
if (options.highlight) {
post.highlight();
}
}
called with
updatePort({highlight: true});
You can use this pattern with non-booleans too; it's especially good when you have many optional parameters.
Oh yeah, this is actually used a lot in ExtJS code. I like the pattern of named arguments so much that I've implemented it in PHP using the extract function.
Отправить комментарий