You need to study Bertrand Meyer's "Design by Contract" and "Applying Design by Contract" papers - https://news.ycombinator.com/item?id=48358691
There are also ways to turn runtime contract checks into static verification checks. See my other comment for details/links - https://news.ycombinator.com/item?id=50108112