I'm new to Objective-C and trying to figure out what the best way of maintaining the rep invariant of a class is, given that exceptions aren't really an appropriate way of enforcing them. A good example of where this would come up is in the Fraction
class that serves as an example in Kochan's Programming in Objective-C, which has this setter method:
-(void) setDenominator: (int) d {
self.denominator = d;
}
So say part of your rep invariant demands self.denominator != 0
. In Java, for instance, the most straightforward way to enforce that invariant would be to throw an IllegalArgumentException
if 0 is passed, but that doesn't make sense in Objective-C. An alternative would be to add an NSError**
pointer argument to report the problem, but that seems both like it's overkill and like it doesn't suit the nature of the abstraction -- unlike, say, a database connection, we don't expect a zero denominator fraction to occur in normal use. So what's the cleanest solution here? Return an integer error code? Something else that I'm missing?
You could use NSAssert()
:
- (void)setDenominator:(int)d
{
NSAssert(d != 0, @"denominator cannot be 0");
self.denominator = d;
}
Check out this answer
In Cocoa and iOS programmer, exceptions are used to indicate non-recoverable programmer error. When an exception is thrown by the frameworks, it indicates that the frameworks have detected an error state that is both not recoverable and for which the internal state is now undefined.
In such a case it's clearly an illegal non-recoverable state that would lead to a division by zero so it is perfectly legal to raise an exception
Specifically you can raise a NSInvalidArgumentException
as others have suggested.
If you want to go deeper into the topic, you should check out the Error Handling Programming Guide
I don't see why you think an exception would be inappropriate here. Barring any additional constraints, I would just raise an NSInvalidArgumentException.
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