Monday, April 27, 2015

What I want in a language: Named Parameters

Method names and variable names are one of the most powerful tools a programmer has to make his/her code readable and maintainable. So the ability to insert words into the code is very useful. What I would like to see is a parameter list based on names and not order. As we enter an age with defaults and optional parameters this becomes even more helpful.

function recordProfile(name: string, single: true, hetero: true, age: number, waistSize: number) { ... }

recordProfile(name: "Will", single: false, hetero: true, waistSize: 32, age: 32)

This seems fundamentally clearer than:

recordProfile("Will", false, true, 32, 32)

When we call a function we shouldn't force the programmer to go look up what they are actually doing.

Historically this was not done because we were closer to machine code and the order in the parameter list was the order on the stack frame. We also had type checkers that helped make sure you didn't make mistakes in this regard. Language designers typically focussed on making their languages more powerful and not necessarily more expressive. The ability to write the name of the thing you are passing does not add much power, but it allows code to be much more expressive.

So how to do this? It is easy in JavaScript. You just always pass an object and then you pull properties out of it. With destructuring it becomes even easier. But doing it this way would be a convention instead of a language construct so it isn't the best way. A better way would be for a language like TypeScript to embrace this. TypeScript could compile the construct in the example below into the appropriate JavaScript.

No comments:

Post a Comment