Reading recently into some programming languages other then JS. First in Golang, there got presented a proposal for Contracts in the language, saying they could avoid introducing generics. Watching a talk about C++ and its future, the concept is proposed and believed to get to the language in C++23. Then I saw a talk of Douglas Crockford from 2006. With the desire for of contracts, as some solution, that could be an alternative for OOP.

I was thinking about Contracts, and what they really are. Getting hit with this concept from multiple directions, it got my attention. Searching for a closer description of contracts, I found that D-lang is a language that has contracts today. They are described as assertions. Within the function. Depending on the Languages syntax, they are allowed to be written all above the actual function, a it like declarator. The assertions could verify a type of existing behavior of input parameter or types and the methods return values. The contract could even describe expected errors.

The very nice thing about contracts, as a language feature is: that they are a zero cost abstraction or even an abstraction with negative cost. When compiler and tools take advantage of the definitions in a contract, they are able to optimize the methods byte-code. allowing it to potentially to save memory and the number of instructions needed for execution. At the very least, contracts are able to show errors at compile time.

The Contracts are told to be a great tool, to describe interfaces more precise. Interfaces ususaly (in go, java, typescript), define existing methods on a type/class and their arguments and return types. But they rarely define the behavior. Behavior today is mostly defined in tests.

How about JS. Assertions exists in Javascript basically from the beginning. I mean, they are just functions, that throw when the argument is not truethy. In JS we are used to compile our code a lot, so much so, that sometimes it is hard to recognize the code running in the browser. A small tool, that has integrations to multiple JS tool chains, is unassert. Unassert simply does one thing, it removes assert calls. So during development assert statements are able to throw errors during tests or in a test environment such as QA or staging. In production how ever, the assertions are able to get removed completely. And more then this. As generally used minifier use smart algorithms, such as tree-shaking, while compiling. They are able to remove lots of code, optimizing the execution at runtime.

It makes me very confident to say, Javascript has contracts today, still recognizing the lack of type-information and the potential that other languages will be able to leverage by introducing extra analysis or special syntax allowing the developer to provide more information to optimize the runtime.

Contents