4 ms·
Minimal JavaScript Assertions Library Ok6.js
- galaxyLogic 6y agoThe thing about assertions is they must be easy to write and easy to read. Like: ok(1 < 2) sounds not too long. Assertions are important because they verify that the code does what its author thinks it does. But they also allow whoever reads the code to know what it is doing, IF it does not crash. From the fact that the program does not crash we can infer that its assertions accurately describe its dynamically changing state. Assertions are a way for whoever reads and tries to understand the code to "see inside" the variables visible in the readable code. Assertions tell you something about the dynamic behavior of the code even if you are just plain reading it. And unlike with debugging what the assertions state about the code is always true, as long as the program does not crash. In short I think that the benefits of assertions for code-understanding are not commonly appreciated as much as they should. It is not only about code-verification. It is as much about code-understanding. Errors are often caused by the programmers making faulty assumptions about the current state of the executing program. Assertions let us know the assumptions we should be making from the code itself. So if we see assertions as a tool for program understanding, it also follows that the assertions themselves should be easy to read and understand. Keeping them short and simple helps in this respect. Assertions work great with unit-tests. Unit-tests provide inputs, and assertions verify that the program responds and behaves like we think it should when called with such inputs.