Saturday, 8 February 2014

Sentence-like function declarations

One of my JavaScript functions had this declaration:
function deviation(words, ideal, maxWords) { ...
My biggest problem with this is that one cannot be sure what the role of the parameters is just by looking at the declaration. A possible solution could be to add a comment. That's a last resort: I believe that code should be simple and self-descriptive enough to be understood without comments. And here is my final refactoring that I like a lot but I've never seen anything like this before:
function calculateDeviation(
    ofWords, fromIdealSize, usingMaxWordsInOneGroup) { ...
There are benefits and disadvantages to this. The main benefit is that now it is obvious what the role of the parameters are without reading the body of the function or the documentation. The main disadvantage is that the parameter names are a bit weird when you use them through the body of the function. Maybe the ideal solution is to add a call-through function to the interfaces (exports if you use require or public methods if you use some kind of OO pattern): so someone who calls this function will know what the parameters are by reading the declaration only but at the same time you can use not-so-weird parameter names in the body of the private function.