by phase_9 · 12y ago · 0 comments
For me; one of the "joys" of coding JavaScript is the expressiveness that comes with a dynamic languages; should you throw an ArgumentError when your function that expects a number is invoked with a String? Maybe - sure it can help catch problems early and effectively "stop-the-line" in your public API, but then again it will probably end up throwing the classic `TypeError: Object foo has no method 'bar'` for you anyway.
For "public" methods which form part of an API (especially when that API is going to be shared outside of my team) I try to make my functions handle failure early (before they delegate off to the "private" internal methods), even better if the public methods can repair any unexpected usage, ie:
function convertToHex(value) {
var result;
if (typeof value !== "number") {
result = convertToHex(parseInt(value, 10));
}
else {
result = "0x" + value.toString(16);
}
return result;
}
Also, with regards to default argument values, I've always felt the "native" JavaScript approach was fairly compact and descriptive when required: function doFoo(bar) {
bar = (bar !== undefined) ? bar : "default_value";
}
[0] http://en.wikipedia.org/wiki/Duck_typing function doFoo(bar) {
bar = (bar !== undefined) ? bar : "default_value";
}
Over : function doFoo(bar) {
bar = bar || "default_value";
}
Coercion avoidance ?Keep in mind that you will have to go for the first option (or other better options) if you expect 'falsy' values to be passed as arguments.
Trusting you find Dart, Typescript, et al agreeable you have to concede that some people are working with legacy code and can only make iterative changes to their codebase?