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?