Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you check for Assigned(self) in object methods?

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.

like image 332
Mark Elder Avatar asked Jun 24 '09 20:06

Mark Elder


1 Answers

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.

like image 93
SeanX Avatar answered Sep 28 '22 01:09

SeanX