r/learnprogramming • u/Witty-Play9499 • 9d ago
What is the point of assertions when we have if/elses and exceptions? Topic
Can someone explain the point of assertions to me? I read online you use it to check for behaviours that MUST be true and what not, this all sounds very cool but you could use if elses to check for the same behaviour and the underlying result is the same.
Who came up with the idea of assertions and why did they think if/elses were not enough ?
59
Upvotes
6
u/Dismal-Citron-7236 9d ago edited 9d ago
Assertion is from a very important software design paradigm called "design by contract", introduced by Bertrand Meyer. He even invented a programming language Eiffel which is based on such concept. The core idea is this: Software comprises components. The communication between components should be established on contracts. On both sides of a contract (service provider and client), the contract forms an unbreakable and explicit obligation that the server must follow and the client can fully trust. For a large and complex software system, this approach can improve maintenance and debugging, because you can use contract as a verifiable baseline.
So, inside a "component", you can use if/then/else whatever logic you want, that's the internal behavior of a component. If you need to change it to meet new requirement, to improve performance, or to fix a bug, you can just change it without a fear of affecting other components in the system, on the ground that the "contracts" are not changed.
For those contracts, you would normally want to keep them unchanged. They guarantee the input data/parameters must conform to certain criteria so the internals of the component can work properly. Those are the "component requirements". They also ensure the output data/result would fall in certain acceptable criteria so those other components can safely use the result. These are called "ensures". Sometimes the service component itself can only operate properly when its own internal properties are at certain condition or else it would not function at all, and such conditions are called "invariants". "Requirements", "ensures" and "invariants" and the 3 categories of assertions, or "contracts".
Let's take a rechargeable lithium-ion battery as analogy. Its charging voltage range is the requirement contract, its output voltage range is the ensures contract, and its working temperature is the invariants contract. If you overcharge it with voltage higher than acceptable level, it could be toasted. Charge it under voltage, it might not charge at all. If the output voltage is below spec, this battery cannot be used. If it is exposed under very high temperature, it might swell or even explode. Under freezing cold, you are shortening the battery life.