I often feel that there's something wrong when I code blocks such as:
function foo (arg){ // arg: a SomeClass object
...
}
or
function foo (arg){
if (Object.prototype.toString.apply(arg) !== '[object Array]')
throw new Error("Parameter must be an array");
...
}
. With a statically typed language I wouldn't have to either clarify the expected argument type or check compliance to this expectation. In addition, the possibility of specifying a return type makes the code even more descriptive.
OTOH some cases lend themselves to self-documenting code:
function parse (json){
...
}
. In the example above, it's reasonable enough to suppose that your API consumers will know both what the function is supposed to do, and what argument values will be acceptable.
However other times clarifying the code intent by choosing "clarifying" names would yield long, awkward names that mix the expected type of a variable and its role.
Am I using dynamic languages with the wrong mindset?
What conventions, techniques, patterns can save one from having to write ugly type-checking code and/or excessively depending on comments?
Someclass
is already documented, so when it is passed into functionfoo
, its purpose is already apparent. And I assume you've already chosen a meaningful name forfoo
. If you're trying to force static typing onto a dynamic language I think you're missing the point.