Objective C protocols usage - objective-c

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 stores contact
information. The address book may contain many entity types e.g. Human
being, a company or anything else that has a contact information.
Now instead of explicitly checking every object type write a
protocol that declares how an object must behave and successfully
appear in your address book.
My understanding and efforts of answering this question is,
Build a protocol which has common methods of each type of contact information under #required tag. And all other methods which are not similar in different contact(Such as fax number has association with company but not person...) under #optional. At runtime you can check whether an object responds to any given method by using selector.
Doubt : However this is again explicitly checking object type indirectly, am I right?
My second thought is to use something like abstract class in java. Which means inherited class's from abstract class implements their own abstract methods. How ever as a naive iOS developer I don't know how to implement this? and I am not sure whether this is going to solve my problem. I would like get enlighten if someone knows this.
External Reading done so far, Please let me know if the answer I am looking for is in one of these links. I will read it again to understand and solve this :). thanks.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15-TPXREF144
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15-TPXREF146
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15-TPXREF149

A protocol is the same thing as a Java interface. It just defines which methods the class should support. Here's a page that explains it clearly: http://www.otierney.net/objective-c.html#protocols
Essentially if you want to make sure a class will have a phoneNumber method (accessor to the phoneNumber property) you would do something like this:
#protocol ContactProtocol
-(void) phoneNumber;
#end
#interface Person: NSObject <ContactProtocol> {
...
}
#interface Company: NSObject <ContactProtocol> {
...
}
And then at compile time (or live for xcode 4) it will tell you if you forgot to add the phoneNumber method to the Person or Company classes.

However this is again explicitly checking object type indirectly, am I right?
No, checking behavior is different from checking type. You can send -respondsToSelector: to any object, and if the result is YES you can send the message regardless of the object's type. You can also require that an object implement a given protocol, again without caring about its actual type:
id<SomeProtocol> foo; // foo points to any type that implements SomeProtocol
My second thought is to use something like abstract class in java.
That could work, but it's apparently not what your assignment asked for, right? It says "...write a protocol..."
Objective-C doesn't provide a way to explicitly make a class abstract the way Java does. You just create the class, and if you don't want it to be instantiated directly you document that somewhere.

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.

Related

Registering all classes that inherit from a particular abstract class in Kotlin

I have a singleton object called registry.
I also have an abstract base class, say Operation with an abstract field called name. I expect other people to subclass this abstract class and create classes denoting specific operations. I want to be able to store name -> Subclass mapping in my registry object.
Ideally, people who subclass this will not even know about this registration. But if that is unavoidable, I prefer them to write as little code as possible just next to their class declaration.
What is the best way of doing this?
The issue here is name being abstract.
If name were a constructor parameter, then you could simply put the code in the your abstract class's constructor. Every subclass, sub-subclass,… instance will call that constructor (directly or indirectly), so it would always get called. (That doesn't apply to a few special cases such as deserialisation and cloning, so you might have to handle those explicitly.)
However, your abstract class's constructor will get called before the sub(sub…)class constructor(s), and so the instance won't be fully initialised and its name property might not be available yet.
The options I see are:
Refactor your class so that the name is a constructor parameter (and can't be changed thereafter), and add your code to the constructor. (If that restriction is feasible, then this is the simplest solution, both for you and for implementers of subclasses, who won't need to do anything extra.)
Provide a method that subclasses can call once the name has been set up. (You'll have to make it clear in the documentation that subclasses must call that method; unfortunately, I don't know of any way to enforce it.)
It may be possible to use annotations and compiler plug-ins and/or runtime libraries, similar to frameworks such as Spring. But I don't know the details, and that's likely to take much more work; it may also need your implementers to add plug-ins and/or libraries to their project, so probably isn't worth it unless you're doing a lot of other frameworky stuff too.
In each case, you can get the name value and the concrete subclass (using this::class or this::class.java), and store them in your registry. (It doesn't look like you're asking about the internals of the registry; I assume you have that side of things covered.)

Is it correct to return an object which class is not the expected class?

Well, i hope you understand me. I have two classes, A and B. B is subclass of A. They have the same public methods and means the same thing, but B does some things a little different, so it has additional methods and attributes that only uses itself. Let say, class A implements a method newFromWizard that interactively creates an object. Can I implement logic for, depending on the user input, create an object A or and object B in the newFromWizard method of A. I mean, can i create a B object from that method of A? Or i need to implement that elsewhere? How is the best way to do it? In practice, i can. But, it is correct for OOP?
By the way, if that matters, i'm using Smalltalk.
Yes, this is a well-known pattern in OO. In the Objective-C Cocoa libraries you'll find it applied systematically, and is known as class clusters. The result is that the Cocoa libraries are much easier to understand than the equivalent c# or java ones. It allows the hiding of a inheritance hierarchy behind an abstract class that has class side creation methods that return subclasses.
public class A{
public B method(){
B b = new B();
return b;
}
}
class B extends A{
}
If this is what you're talking about, it's valid.
I would say that it's not intuitive way of doing things. Let's simplify it and say that you just redefine new. Then in some point you do A new and get an instance of B. The thing that they are similar makes it not so bad. But imagine that someone else starts working with your code. And hew knows that message new should result in creation of the instance of the receiver. And then something goes different. I'd say that conceptually it's wrong. Why now to implements some builder class? And have there something like
createInstanceOfAB
|className|
className := "do what you need".
^ className asClass new.
This is a more clear way.
Once again you can make new… method to do whatever you want, even shoot fireworks, but most of the people will expect it to create instance of the same class
I think you shouldn't worry too much about whether it is "clean OO" to return an instance of a subclass. It's being used and done so often because it is very helpful and makes your code very readable compared to somme kind of factories and stuff.
My biggest concern here would be that you should name your class method carefully. Don't use #new is probably the most important rule, but you should always use a name that already says: give me an instance of what is appropriate right now.
I'd say this is not limited to subclasses, such a method can even return objects that do not inherit from the class. In a dynamically typed language, this is okay. Remember, we're in a dynamically typed language, so as long as you have polymorphic interfaces, the class of an object is not really important to its users as long as it responds to your message sends...

Find out what superclasses contain property or method implementations

If I have properly documented a method or property, I can find out where it was defined by typing help class/method, which will tell me Help for class/method is inherited from superclass otherclass.
Often, this means there is a method definition there too, but not necessarily (I might implemented an abstract method without re-documenting it).
In the general case, how can I find out what superclass(es) define a particular property or method?
I'd like to know because I'm refactoring my code.
NB: I'm using classdef-files and all my classes are handle classes, should it be relevant.
Using the ? character you can find out meta data about your class: lst = ?yourClass
in lst.PropertyList(1).DefiningClass you will find where the property on index 1 originates from.
in lst.MethodList(1).DefiningClass you will find where the method on index 1 originates from.

The Magician and the custom class – understanding the header and implementation file

I am taking my first stumbling steps in the Objective-C world together with a book on the subject. I have now come to the stage in which to internalize the concept of creating and using a custom class.
And as I guess that understanding these fundamental concepts and principles correctly is key to my future learning of Objective-C, I just wanted to check with you if have grasped the concepts somewhat correctly.
So when creating a custom class, I have understood that this is done in two separate files – the public class header file, and the class implementation file. And in order to internalize this concept, I have metaphorically understood this with a parallel to a “magician” doing its tricks in front of an audience.
The header file is somewhat like the poster outside the theatre where the magician performs. Before entering, we can all see what the magician looks like (the properties) and what tricks he (it’s mostly a “he”) can perform (the methods), and on what types of stuff he can make his magic tricks (type declaration). Thus from this “public” poster (the header file) of the magician, I can understand what kind of magic he can perform and what props he is using. Maybe there is also a mentioning of that this particular magician has learned some of his tricks from the great Houdini (the class heritage and Houdini thus being the superclass).
If I were allowed backstage, I would then be able to actually see how he is doing his tricks, that is, I would be able to look in the magicians implementation file.
Would this metaphor be somewhat along the lines of how you can understand the concept of a custom class?
However, I have not yet quite figured out how the concept of class methods and instance methods relates to this metaphor?
Could you say that instance methods belongs to a category of tricks that this particular “instance” of the magician is performing in this particular show, and the class methods would be the tricks that contemporary magicians can perform?
Thirdly, it is a bit confusing the way methods are using “types”. Some seem to be declared up front in the interface file, and some seem to just be “declared” on the fly within the methods?
To take an example using the “Magician” class, my understanding of the header file might look like this:
#interface Magician : NSHoudini
// Instance method that given a variable of type rat it will turn this into something of type rabit
- (rabit) FromRatToRabit: (rat) aRat;
#end
And the implementation file might look like this:
#import “Magician.h”
#implementation Magician
rabit aRabit
// rabit being the type and aRabit the variable
- (rabit) FromRatToRabit:(rat)aRat;
{
// some magic code goes here which will take what’s in the aRat variable, of type rat
// and turn it into a form of type rabit and return it in the aRabit variable
aRabit
}
#end
If above is correct I wonder why the aRat variable that you “feed” the method with is not declared? Or is the declaration considered done when you are using it in the method description?
Your metaphor is acceptable. A header is an interface for other files to look at which tell them what is accessible to them from that class/file and its corresponding implementation file (if it has one)
I noticed in your code though that Magician is a subclass of Houdini. I might just be misunderstanding your example, but in terms of inheritance, that is probably incorrect. What you are saying there is that every Magician is a type of Houdini. It should probably be reversed to say that Houdini is a type of Magician.
Class vs Instance has been explained many times and is not specific to Objective C, so I won't get into it too much.
Here is a post with some good answers. Basically, a class function/variable belongs to the Class itself, and is not specific to any instance of that class. Another word for a class function/variable is a static function or variable.
Not sure what you mean by the last question. Every pointer/variable in objective c has a type.
Your syntax is messed up though, Here is what the code you posted should probably look like (and yes I corrected the spelling of rabbit :-P)
#interface Houdini : Magician
// Instance method that given a variable of type rat it will turn this into something of type rabit
- (Rabbit *) FromRatToRabit: (Rat *) aRat;
#end
#import “Houdini.h”
#implementation Houdini
Rabbit *aRabbit; // this is an ivar, although you're not actually using it anywhere, I'm just correcting your syntax
- (Rabbit *) fromRatToRabit:(Rat *)aRat;
{
// some magic code goes here which will take what’s in the aRat variable, of type rat
// and turn it into a form of type rabit and return it in the aRabit variable
[aRat doSomethingToReturnRabbit]; // assuming rat has an instance function that returns a rabbit
}
#end
And you could use this function by doing something like
Houdini *myHoudini = [[Houdini alloc] init];
Rat *houdinisRat = [[Rat alloc] init];
Rabbit *houdinisRabbit = [myHoudini fromRatToRabbit:houdinisRat];
Note that this depends on there being a rat class and a rabbit class (which you did not provide). I am also just using what are normally the default initializers.
Hopefully this helps, you should try searching more on the specific topics you have questions on individually, because there is plenty of reading available.
It's a great metaphor for understanding the divide between the public interface and the hidden implementation. But I think you might be getting a bit wrapped up in it and I do see two major misunderstandings - "Houdini" being the superclass and the class methods being "all tricks".
The common textbook way to evaluate the sensibleness of an inheritance hierarchy is to evaluate whether a subclass instance "is a" superclass instance. This can get very abstract in reality but if, say, you're designing the Magician's Guild medical insurance benefits processing software or something, in that context a Magician "is a" something that's definitely not a Houdini! Say they are all freelancers so every Magician "is a" 1099 Contractor (US tax form for self-employment income), or something like that. Another way to think of it would be to think Magician "is a" Stage Performer, which "is a" Entertainer, and so forth. Not that you always want to make software like this but it can help for learning the concept I suppose.
The second thing you said you were struggling with was how to think about class methods. Consider class methods behavior and information inherent to the type, and independent of any instance. Going back to the benefits software example, lets say all Magician guild members get a 401k (another US tax code thing, retirement account) with $X defined contribution per paycheck. Now assuming that's not something that varies with seniority, this would be a good piece of information to keep at the class level. So, all the tricks a magician can perform would not be class methods - Magicians perform them, so they would be instance methods. Perhaps a list of banned tricks (for being too dangerous) could be a class method - it's a rule inherent to being a Magician but is independent from any single magician.
Finally, to your third question about types, I can sort of guess at what you're asking but am not sure. Say you have a method
- (void)myMethod:(id)myArgument
{
NSLog(#"myArgument = %#",myArgument);
}
Then are you asking where myArgument is declared? It is declared right there in the method signature, where it's a parameter to the method and you can refer to it in its scope of the method body (within the curly braces). Not sure if that's what you meant by "on the fly" or not. I'm afraid you'll have to provide some actual source code, not pseudocode, and point out specific places you're wondering about.
And a couple of minor points on terminology, sorry this is getting so long - the term for "feeding" a value to a method is "passing" usually as a "parameter" or an "argument". The method "description" is usually called a a method signature, or declaration, sometimes prototype I hear. And yes, please clarify what you're talking about with types, type declarations, and so on, I'm not 100% clear on your questions there.
Hope this helps!

OOP design issue: Polymorphism

I'm trying to solve a design issue using inheritance based polymorphism and dynamic binding. I have an abstract superclass and two subclasses. The superclass contains common behaviour. SubClassA and SubClassB define some different methods:
SubClassA defines a method performTransform(), but SubClassB does not.
So the following example
1 var v:SuperClass;
2 var b:SubClassB = new SubClassB();
3 v = b;
4 v.performTransform();
would cause a compile error on line 4 as performTransform() is not defined in the superclass. We can get it to compile by casting...
(v as SubClassA).performTransform();
however, this will cause a runtime exception to be thrown as v is actually an instance of SubClassB, which also does not define performTransform()
So we can get around that by testing the type of an object before casting it:
if( typeof v == SubClassA)
{
(cast v to SubClassA).performTransform();
}
That will ensure that we only call performTransform() on v's that are instances of SubClassA. That's a pretty inelegant solution to my eyes, but at least its safe. I have used interface based polymorphism (interface meaning
a type that can't
be instantiated and defines the API of classes that implement it) in the past, but that also feels clunky. For the above case, if SubClassA and SubClassB implemented ISuperClass
that defined performTransform, then they would both have to implement performTransform(). If SubClassB had no real need for a performTransform() you would have to implement an empty function.
There must be a design pattern out there that addresses the issue.
My immediate comment is that your object modelling is wrong. Why treat SubClassA as a SuperClass (is-a relationship), when I would suggest that it's not.
You could implement a dummy performTransform() that does absolutely nothing in its base instance, and is overridden in SubClassA. But I'm still concerned that on one hand you're treating all these objects (SubClassA, SubClassB) as the same thing, and then wanting to treat them differently depending on their real implementation, rather than the interface they present.
Assuming you are using a strongly-typed language, which your question seems to indicate...
There is no design pattern to work around this, because this is the intended behavior.
In your definition, performTransform belongs only to SubClassA. Thus, to be able to invoke performTransform on an object, the object must be of type SubClassA (or a subtype of SubClassA.
Invoking performTransform on a SuperClass does not make sense because not every instance of SuperClass defines this method.
Downcasting from a SuperClass to a SubClassA should certainly throw an error if the instance is not a SubClassA - this should be obvious.
So, you must either change your definitions such that performTransform belongs to SuperClass (in which case, as you said, every instance of type SuperClass would need to have some implementation for the method, even an empty one) or you must make sure that you are only invoking methods on types that define them.
I'm not so sure it requires a pattern to solve but instead just a small redesign. If it makes sense for anything to call performTransform is should be in the superclass as a virtual method and overridden in the subclasses.
So the superclass defines the flow from an abstract viewpoint and the subclasses implement them appropriately. In your case, the simplest options are to either just leave performTransform empty in the superclass or implement it as an empty method in the subclass that doesn't require it (when you mix this approach with a short comment, you get a more maintainable system IMO).
The closest pattern I can think of for this is the Null Object pattern where this performTransform method is just a dummy function to preserve compatibility but perform no actual task.
Just because you say your bicycle is a car doesn't mean there's a place to put gas in it. The whole point of polymorphism is to let you think of things as the super class - these are all bank accounts, these are all shapes, to use the classic examples - and not get caught up in what they really are. Sometimes the subclasses add capability. In many cases that capability is used in the specific implementations in each subclass. So to use your names, some method Adjust() that is in the signature of SuperClass is implemented (differently) in SubClassA and SubClassB. The SubClassA version calls its own performTransform as part of the process and we all live happily ever after. The minute some code needs to decide whether to call performTransform or not, you're not just thinking of it as a SuperClass any more. That's not necessarily something that needs to be solved, it's just what is.
It Would be better to have the call to performTransform() in a method that only takes type SubClassB as a parameter - at least you wouldn't have to do type checking then.
On saying that, if your having this problem at all it may suggest that inheritance may not be the best solution - composition may be a better way to approach the problem.