I’m learning objective-c from “Programming in objective-c” author Kochan. 3rd edition.
In Chapter 8 “Inheritance” Mr. Kochan gives following explanation to the method:
-(void) setOrigin: (XYPoint *) pt
{
if (! origin)
origin = [[XYPoint alloc] init];
origin.x = pt.x;
origin.y = pt.y;
}
“The method first tests to see if the instance variable origin is nonzero (make sure you
understand that test and the use of the logical negation operator ! that’s used). Recall that
all instance variables are initially set to zero. So when a new Rectangle object is allocated,
its instance variables, which includes origin, will be set to zero.
If the origin is zero, the setOrigin: method will allocate and initialize a new
XYPoint object and store the reference to it in the origin.”
Is there a logical mistake? Doesn’t the “setOrigin” method allocates a new XYPoint object only if the origin is non zero?
The author is, indeed, correct.
This is why I don’t like incomplete comparisons in C.
If he codes
if (origin)then that boolean expression is true for any value oforiginwhich is non-zero.So, when he negates it, the boolean expression
if (! origin)is true only when origin is zero.IMO, this is horrendous and should be coded
if (origin == NULL)which makes it much clearer.It seems to me that he is going out of his way to teach bad coding habits. This sort of construct always gives off a Code Smell.