Thursday, July 30, 2015

Javascript backend: Static Type Syntax

Every fucking time i see this error message in my chrome js console, Uncaught TypeError: Cannot read property `position` of undefined makes me want to walk into Google's head office and beat every mother fucker down. It is time for Lars Bak and Kasper Lund at Google to give up on Dart, and provide a real debugger for Chrome.

Programmers can get into heated debates about syntax and static typing. Sure, it is nice to have a compiler check the types of every variable at compile time, and then throw errors for any typing mistakes you have made, and this works well for native apps written in a statically typed language, but not in the web browser.

Dart and TypeScript compile to JavaScript, and try to offer the same safety that static types provide. However, this is not actually useful because JavaScript is itself not typed, and the type of a variable can change at anytime.

The reality is that in any real web application, you are going to be interfacing with many external JavaScript libraries, and most of your type errors are going to happen at runtime when using those libraries. So you really need a good runtime type checker that will provide useful errors so you can debug your code quickly. JavaScript without runtime type checking, is very hard to debug, because many types of errors are silent, and often this causes later code to break with confusing error messages about something being undefined, forcing you to manually trace the logic back to the original thing that was wrong and caused the whole chain of problems.

Runtime Type Checking Syntax

example source code

def setup_camera_untyped( c ):
 c.position.z = 60
 c.position.x = 5

The function above expects the argument c to be an instance of THREE.PerspectiveCamera. However, if you make a mistake and call the function and pass undefined or some other type, it will fail at runtime with this error message which is almost completely useless.

typed version

def setup_camera( c:THREE.PerspectiveCamera ):
 c.position.z = 60
 c.position.x = 5

Above is the same function with c typed as THREE.PerspectiveCamera, this instructs the transpiler to inject runtime type checking code, that when fails, throws and error message you can actually use to fix the problem, like what is the function and variable name.

For more info see the wiki page, here.

No comments:

Post a Comment