-1

I usually do Javascript and I like putting console.assert liberally in my application. It throws an error if the first argument is falsey. E.g.:

console.assert(price > 0, 'Price isn\'t above 0')

It's easy to automatically remove this for production builds. When developing, I often accidentally break an assertion. I think this is better than unit tests, at least during the early stages of development, because:

  1. development application state is more realistic than test states

  2. assertions are easier to write, so developers will write more of them

Also, for a big enough application, I think it'll be good to keep the assertions in production for 1% of users. It's better to have it fail for 1% of users than to have silent errors for everyone.

However, I've never seen any tech companies do this. Why is that?

3
2

You should rely on specific exceptions you can propagate up or special return values since your code will be living with all sorts of code in an app that lives with all sorts of apps in its overall system. Assertions in source code cause clutter and using them in lieu of properly defined behavior leaves you with all sorts of headaches in the long term since you cannot handle it outside the involved code.

It just so happens that all the benefits you want to get with them e.g. preventing addition of code that breaks things you can get by having them in unit tests. It also takes about a few seconds in a modern IDE to hit the ground running writing up some unit tests. Hence why you do not see assertions beyond teaching samples in the source code itself.

1

Assertions to me were always about documenting my assumptions related to the functioning of an algorithm.

They communicate that, at this point, I’m asserting something should be true—likely, it’s a property I can prove to be true of a functioning implementation. For example, in a Semaphore implementation, I might have asserts that the value is never below zero. No one should ever see that fail—if they do, my implementation is simply wrong.

They cannot replace proper tests or « handling the unexpected ».

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.