Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

maintaining rep invariants in Objective-C

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?

like image 926
artes_subtiliores Avatar asked Dec 06 '12 22:12

artes_subtiliores


3 Answers

You could use NSAssert():

- (void)setDenominator:(int)d
{
    NSAssert(d != 0, @"denominator cannot be 0");
    self.denominator = d;
}
like image 186
mipadi Avatar answered Oct 31 '22 17:10

mipadi


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

like image 2
Gabriele Petronella Avatar answered Oct 31 '22 17:10

Gabriele Petronella


I don't see why you think an exception would be inappropriate here. Barring any additional constraints, I would just raise an NSInvalidArgumentException.

like image 1
Chuck Avatar answered Oct 31 '22 18:10

Chuck