Objective C protocols usage

前端 未结 3 1323
太阳男子
太阳男子 2020-12-05 08:00

I have a homework question which confused me, really badly. Below is a brief explanation of a question.

Imagine you are developing an application that

3条回答
  •  春和景丽
    2020-12-05 08:41

    You have ... options.

    Optional methods are convenient for the person writing the class to conform to the protocol, annoying for the person making use of the protocol. So it depends who you are trying to please.

    Optional methods are not as bad as checking type. Imagine how the code would look when accessing a contactable entity object. When you use an optional method, you have to have an if case and an else case. It's not as convenient as just going ahead and assuming you can call the method. But it's way more convenient than checking type. That would be one if case for each different type of entity (and an else case, which might be an assertion). Additionally, if you use optional methods, information about the entity is encapsulated in its class. If you check type before calling a method, then the information about what type of contact information an entity provides is outside the class in the calling code. If you upgrade the entity to provide an additional type of contact, that improvement is not available until you update the calling code.

    Option B is to make all the methods required, but give them the option of returning a value that indicates that no information is available, such as nil. Of course that still means an if case to check for a nil result, it's just less verbose. An even better solution for this problem is to have the methods return collections of multiple contacts. After all, people can have more than one phone number. Then to indicate that a contact type is not applicable, you would just return an empty collection.

    The downside is that whoever writes the class that conforms to the protocol has to add a simple stub method that says return nil or something.

提交回复
热议问题