Subclassing RuntimeException to support Assertions

“Programming by contract” is a style of programming where you see the various parts as having a contract to provide certain conditions etc for each other. They will verify those conditions, and refuse to work if not satisfied.

I have used Assertions very successfully for many years in other languages. At the start of a procedure you verify the conditions, and my experience is that this makes debugging much easier.

I found Matt Neuburgs old book, obsolete in many places, but still helpful, and it talks about this on page 250. He subclasses RuntimeException and I can do that, but the code he provides doesn’t seem to work anymore. I subclass RuntimeException and call it “assertion”, and add a method assert

This is the code he writes in the book:
Sub assert (b as boolean, s as string)
text = s
if not b then
raise me
end if
Exception err as assertion
MsgBox err.text

The problem is that xoxo wants something to end the exception. What should this look like today ?

let me get my copy out and see :stuck_out_tongue:

ah I see what he’s done (in mine its on pages 212 - 213 which is the first edition)
it requires you to create an single global instance

I would

  1. create the class “assertion”
  2. add a “shared method” assert - this gets rid of the need for a global singleton - as follows
Public Shared Sub assert(b as boolean, s as string)
    if not b then 
      raise new assertion(s)
    end if
  catch err as assertion
    MsgBox err.Message
  end try
End Sub
  1. add a constructor as - making it protected so the only way yo ucan construct one is via the shared method
Protected Sub Constructor(s as string)
  me.Message = s
End Sub
  1. then you can use it like
dim d as new date
assertion.assert(d.year = 1999, "illegal year")

Its much the same idea as Matt had but since the book was written there have been things added (like shared methods) that remove the need for some of what he had to do way back then