Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred way of returning an immutable object

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 ?

like image 202
Peter Warbo Avatar asked Dec 20 '12 13:12

Peter Warbo


People also ask

What is object immutability Why is it preferred?

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).

How do you change immutable objects?

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.

Can we change the immutable object?

Immutable class in java means that once an object is created, we cannot change its content.


1 Answers

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.

like image 122
Ismael Avatar answered Sep 30 '22 01:09

Ismael