I am looking at some code (Delphi 7) with following check is at the top of every method call for a specific object:
if not Assigned(self) then
raise Exception.CreateRes(@sAbstractError);
{ Real code for this method}
I guess that this would prevent me from trying to call a method on a null object pointer. But I would get an exception as soon as I tried to access member data in that case anyway, right?
Is this some type of standard that I have never seen before? The object in question derives from TPersistent.
You can call a instance method on a null pointer although it's not the sort of thing you want to do deliberately. When that happens, execution continues along quite happily until it needs to access the instance data and then it all goes bang.
In that case, checking for nil would alert you at the top of the procedure so you could do something different such as logging a stack trace. Or you could put a break point on the raise line so you can dive in and see what is happening.
Ie, it's something that I might do if I had a specific bug I was trying to track down where a nil reference was being used.
Doing it regularly strikes me as a code smell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With