I've written my add: methods taking id object as an argument and returning an id object. However in one I assign result as an id variable and in the other I leave it as a class object.
-(id) add: (id) f
{
// To add two fractions
// a/b + c/d = ((a*d) + (b*c)) / (b * d)
// result will store the result of the addition
id result = [[Fraction alloc] init];
int resultNum, resultDenom;
resultNum = numerator * [f denominator] + denominator * [f numerator];
resultDenom = denominator * [f denominator];
[result setTo: resultNum over: resultDenom];
[result reduce];
return result;
[result release];
}
AND
-(id) add: (id) f
{
Complex *result = [[Complex alloc] init];
[result setReal: real + [f real] andImaginary: imaginary + [f imaginary]];
return result;
[result release];
}
Can someone tell me which approach is best or does it not really matter?
I don't think I fully understand what
id result = [[Fraction alloc] init];
actually does so any clarification on that would be greatly appreciated too.
My understanding of it is that it performs the same function as Fraction *result but does not explicitly set the object type. As such it is dynamic typed and so it's checked at runtime to see if the methods I call on it work with it or not. Am I correct in thinking this method isn't preferred as errors may appear at runtime rather than compile time and I should use static typing when I know what type of object is being used?
Hopefully that makes sense, not sure it did to me.
