Suggestion: assert and verify 'macros'

Monkey Forums/Monkey Programming/Suggestion: assert and verify 'macros'

Gerry Quinn(Posted 2012) [#1]
I was just reading a post about unit testing this morning. That's not really my thing, but it reminded me that when coding in MSVC I liked to use their ASSERT macro liberally. It would be easy to add to Monkey, I think, even without taking any steps towards a true preprocessor.

' Typical assert
#ASSERT a = 3

' Translation
#If CONFIG = "debug"
	If Not ( a = 3 )
		DebugStop()
	End
#End


' Typical verify
#VERIFY CountMonsters() = 10

' Translation
#If CONFIG = "debug"
	If Not ( CountMonsters() = 10 )
		DebugStop()
	End
#Else
	Local dummy:Bool = CountMonsters() = 10
	' ..or use magic to eliminate the dummy variable in release mode, but the above would be fine anyway
#End


I generally just used ASSERT. It is very handy for stopping a program when a function gets unexpected parameters or something, and being immediately able to look at the values (assuming one is in glfw).

Trying to insert DebugStop() statements in the right place is nearly as bad as inserting Print statements!


NoOdle(Posted 2012) [#2]
You could write your own assert functions as a work around for now, diddy has some if you wanted to have a look at some code.


Gerry Quinn(Posted 2012) [#3]
I guess... but it means adding spurious function calls to release code.

On the other hand it seems one can put expressions in parameters like

Assert( x = 5 )

..which I hadn't really thought about. So at least the syntax need not be too clunky.


Shinkiro1(Posted 2012) [#4]
I have made my own assert function, but be aware that you shouldn't use them in loops.
I did that once and found out it was the bottleneck of my app (because of the string creation i guess).


Gerry Quinn(Posted 2012) [#5]
I wouldn't normally use strings: I would just call DebugStop() if in debug mode, like so:

Function assert( condition:Bool )
	#If CONFIG = "debug"
		If Not condition
			DebugStop()
		End
	#End
End



Of course that does mean they only work when you are actually debugging with GLFW, but it also means there's not much overhead (just a call to an empty function).

Of course one could also add further conditions to the above function, e.g. printing something if the target is not GLFW. Maybe one could do something with reflection to identify the caller, I don't really know much about reflection, coming as I do from the C++ side of things.

The ideal would be to not even have the call in release mode, but that would require a preprocessor-style #ASSERT as I suggested at the top.


NoOdle(Posted 2012) [#6]
I have a few different options with mine, it can output a Print or DebugLog or Nothing and can either throw an Error or DebugStop or Nothing.