If I have a method that looks something like this:
- (NSDictionary *)removeDataInDictionary:(NSDictionary *)dictionary {
NSMutableDictionary *mutableDictionary = [dictionary mutableCopy];
[mutableDictionary removeObjectForKey:@"key"];
// Return option 1
return [NSDictionary dictionaryWithDictionary:mutableDictionary];
// Return option 2
return (NSDictionary *) mutableDictionary;
}
Is option 1 "better" codewise because it will really return a NSDictionary
whilst option 2 will actually return a NSMutableDictionary
disguised into a NSDictionary
?
Immutable objects are good Map keys and Set elements, since these typically do not change once created. Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged).
Immutable objects are objects that don't change. You make them, then you can't change them. Instead, if you want to change an immutable object, you must clone it and change the clone while you are creating it. A Java immutable object must have all its fields be internal, private final fields.
Immutable class in java means that once an object is created, we cannot change its content.
The return option 1 will create an immutable NSDictionary
object, which is the way to go if you don't want it to be edited by any means.
The return option 2 will return an NSMutableDictionary
anyways. Casting it to a NSDictionary
will not make any difference
HOWEVER: When calling this method, you will see that it returns an NSDictionary
and thus you will have to consider it as such outside, so unless you check the object class and then cast it to an NSMutableDictionary outside your method, it will look immutable outside.
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