Code Review : Language Features

BASARAT
2 min readJan 29, 2016

--

I’ve previously mentioned that being a great polyglot programmer is hard. But if you focus on a particular language and aim for excellence you can probably do great things with it.

Lets look at this piece of TypeScript code that a new JavaScript developer wrote (creating a padding function for CSSinJS):

Beyond the fact that this function assumes `0` is same as `undefined` (that’s not the focus of this post) its not idiomatic TypeScript. First off it uses any. This leaves it up to the other developer to decipher that the padding function only really excepts number or string. Lets fix that by using TypeScript union types (creating a type called `PaddingUnit` that can be a number or a string:

The next piece of documentation missing in this is what are all the ways that the parameters a, b, c, d intended to be passed in. If you read the code you realize it only expect either

  • just a
  • a AND b
  • a AND b AND c AND d

So the issues are

  • there is nothing stopping someone writing padding(1,1,1) (i.e. only three parameters) and expecting it to work.
  • there meaning of what a / b / c / d represents within the function changes based on the number of parameters, and that isn’t documented either.

The language feature you are looking for is function overloading. Once you add that in you get better documentation:

And this documentation even provides you with safety as shown below:

Atom TypeScript telling you all the valid uses of the padding function

Of course since this was something that was done for other CSS properties as well, it can be neatly abstracted out to become more general (and also use undefined explicitly instead of failing for 0).

Till next time, keep learning🌹

--

--

No responses yet