Search code examples
objective-ccocoaimmutabilitymutable

What's the most efficient way to make immutable and mutable versions of an objective-c class?


Suppose I’m making an Objective-C class that represents a fraction, and want to create immutable and mutable versions.

Following the patterns in the Foundation framework, you might expect to see the method fractionByAddingFraction: in the immutable version and addFraction: in the mutable version.

The paradox I’m running into is how to only include the fraction-adding logic once between the two classes. It seems that the immutable fractionByAddingFraction: method needs to know about (and make use of) the mutable addFraction: method in order to avoid code duplication, and yet including the mutable methods in the implementation of the immutable class means they could conceivably be called on the immutable object, which defeats the point.

A brief explanation (or better still, a continuation of this simplified example) would be much appreciated!


Solution

  • Your approach is correct (if you really need a mutable subclass, which you should avoid unless you actually need it). I'm not quite clear where the confusion is coming in. You would most easily implement addFraction: using fractionByAddingFraction:. It would be a little inefficient, but that's the direction that would make the most sense. Something like:

    - (void)addFraction:(Fraction *)anotherFraction {
       Fraction *newFraction = [self fractionByAddingFraction:anotherFraction];
       self.internalStuff = newFraction.internalStuff;
    }
    

    But typically you would probably handle this more efficiently with some private _GetInternalStuffByAddingInternalStuffs() function that both classes would use.