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!
It's mutable so you can't return it directly from a method. This means you end up doing all sorts of defensive copying. That increases object proliferation. The other major benefit is that immutable objects do not have synchronization issues, by definition.
The meaning of these words is the same in C# programming language; that means the mutable types are those whose data members can be changed after the instance is created but Immutable types are those whose data members can not be changed after the instance is created.
Immutable objects are also useful because they are inherently thread-safe. Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects.
Besides reduced memory usage, immutability allows you to optimize your application by making use of reference- and value equality. This makes it really easy to see if anything has changed. For example a state change in a react component.
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.
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