What is difference between inheritance and category - objective-c

what is the difference between inheritance and category in objective-c
Both are used for the subclass! So what is difference between them

While Category is a nice way to add functionality to the base class, people like me who come from other object oriented technology such as Flash, will find a little difficult to understand as to how this thing relates to the inheritance chain. The same question came up to my mind and I did a quick research on the topic.
The final thing is Category does the same thing as it tells about itself. It adds functionality to the base class. If you remember this, then there would be no confusion at all.
Well, for that to understand, lets take an example. Suppose there is a Class A and Class B is a subclass of Class A. In the application Class B is used in a lot of places. Now, there is a need to add some more functionality to Class A, so a new category is written as "A+newRole". Once this category is written, the new functionality is added to the base class and in this case, Class A. That means, all those classes which are child classes of Class A such as Class B, automatically gets the functionality. Thats freaking cool. One can straight away go ahead and call the new methods added in the Category from the child classes. The only thing necessary here is to import the Category file to the appropriate place.

A category adds extra functionality to a class without generating a new class at all, you just extend it but it does not have polimorphism implied or anyting like it.
Inheritance on the other hand, generates a new class on its own right in which you can add new instance variables and override behavior from the parent class by polimorphism.

Related

Can Coldfusion components share methods without being descendants of the same super class

We have used a homegrown version of object oriented coldfusion for a while and I'm just starting to experiment with cfc's and how it "should" be done...
If I understand correctly, cfinterface defines the signature of functions, and any class that implements that interface must have their own functions to do whats defined in the interface.
I'm kind of trying to do the opposite - the interface doesn't just define the function's signature, but also defines the logic of the function and anything that implements that interface can use its functions without having to define it itself. Does that exist besides creating subclasses?
For example, say you have classes A,B,C,D that all belong to the Animal class
A & B can walk
A & C can talk
B & D can sleep
Suppose the logic of walk, talk & sleep (if the object can do it) is the same regardless of the class doing it
Ideally, if A & B both implement the walking interface, they can walk without defining a separate walk method in each class.
Or borrowing a better example from this java multiple inheritance question
A Pegasus is a mix of a Horse and a Bird because it runs like a horse
but flies like a bird
Is that possible? (I think this is multiple inheritance?)
In short: no, an interface only defines a contract, it does not (and cannot) define functionality). Also CFML does not have the concept of multiple inheritance.
You will have to use single-inheritance and concrete implementations to effect what you need. I can't be bothered assessing your implementation-sharing requirements to work out what an approrpriate class hierarchy might be to minimise code duplication. I'm sure you can do that yourself (and it's not really part of your question anyhow).
One tactic you could try is to use mixins for your common methods. Store the common methods in a different library, and then inject them into your objects as required. So basically Mixins.cfc would implement walk(), talk(), sleep(), and you'd have an AFactory.cfc, BFactory.cfc, CFactory.cfc. When asking a factory for a new A, B or C, and the factory method injects the mixin methods before returning the instances. Obviously this is a fairly cumbersome process, and you'd want to use some sort of IoC container to manage all this.
A better question might come out of you showing us more real world examples... I suspect your domain design could perhaps stand improvement if you find yourself needing to do what your example suggests. Actual design requirements are seldom exposed with examples using animals.
You can do similar things with WireBox and its Virtual Inheritance feature:
http://wiki.coldbox.org/wiki/WireBox.cfm#Virtual_Inheritance
// Declare base CFC
map("BaseModel").to("model.base.BaseModel");
map("UserService").to("model.users.UserService").virtualInheritance("BaseModel");
It's basically very similar to what Adam described above; a base class is created, and references to it's public members are placed in the sub class.
https://github.com/ColdBox/coldbox-platform/blob/master/system/ioc/Builder.cfc#L535
There's no reason why you can't build something similar but you should know this has already been done.
Full disclosure, I am a contributing member of the *Box community.

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

About methods in OOP

I'm relatively new in OOP.
I understand classes, methods, etc, etc but I'm having troubles with the philosophy.
Right now, I'm working on a project to manage projects, with project management, class, methods, variables, users, groups, log and task management.
So, starting with Project class, i've that:
public function create_project()
public function get_projects()
public function delete_project()
Then, ProjectClass class:
public class create_class()
public class get_classes()
public class delete_class()
But then, I though that is not the right way, so I've changed to:
Project class methods:
set_name, get_name (and similar methods)
add_class
get_classes
add_log
get_logs
ProjectClass class methods:
set_project_id (and get)
add_variables (and get)
add_method
...
So, in the first case, is the Project class who create new projects, the ProjectClass class who creates the clases and the Method class who creates the methods, and in the second case, is the Project class who creates and manages its classes and is the ProjectClass class who creates and manages its methods.
So, is any of theses "styles" correct?
If is the second case the correct case, who creates the projects? Itself?
Thank you so much
In the general case it is really hard to tell if a design is better than the other if you don't have clear responsibilities to assign (and by this I mean behavior outside from getters and setters). As time went by I moved away from upfront design to a iterative/incremental one, tackling one problem at a time and refactoring the design as needed. In this case I would try to lay down the basic requirements of your system and start a design-implementation cycle for each of them, re-structuring your model as you go tackling new requirements.
Just an an example consider this question: Does it make sense to have a class that is not bounded to a project? If the answer is no then it can be a good idea to have a method like Project>>createClass(aClassName), since you are explicitly stating that a class is created in the context of a project. Also you can make the proper connections between a class and the project it belongs to inside the method's implementation. However it is also a valid approach to define a constructor in the ProjectClass class that takes a project as a parameter. In that way you are saying "if you want to create a new class, then you must provide the project where it belongs to". Which approach to use depends on many things, one of them being programmer tastes :), so it is really hard to state if one is better than the other without having a specific context to evaluate them.
Finally, if it helps, there are a few things that are worth mentioning:
Assuming that public function create_project() is an instance method, why does an instance of a Project know how to create other projects? At first it doesn't make much sense, since that is basically a class-side responsibility, unless you have a specific motivation for this (e.g. like the Prototype pattern).
Why does a project answer to get_projects()? Are they related in some way? Or it just list all the projects? Then again, this sounds like a class-side responsibility.
I generally don't like to add the concept that the message receiver represents as part of the message. So, I wouldn't call the message delete_project(), since it is redundant to state $project->delete_project() (you already know the receiver of the message is a project).
You should be consistent with your class names. If you use ProjectClass to represent classes then you should use ProjectMethod to represents methods (though I personally don't like these names, IMHO they are misleading). It is quite important to chose proper names and keep them consistent in your domain model.
HTH

Organising refactored code

Please have a look at the code below:
public class Vehicle
'Not very well designed. Contains properties and functions/subs for cars, buses, tractors, planes, drivers etc.
end class
I am wanting to refactor the code so that there is a superclass (vehicle) and many subclasses. I want to do this as I go along whilst working on much higher priorities.
If I create the new classes then there will be two Vehicle classes i.e. the refactored vehicle and the old vehicle. I believe the best approach is to create a new namespace for the refactored code e.g. company.app.businesslogiclayer.automobiles.refactoredcode, company.app.datalogiclayer.automobiles.refactoredcode. Is this the correct approach?
I think you could treat your existing clas as a subclass since it already has some class-specific functionality in it and then look at the Extract Superclass refactoring. Here you would create your new super class and then move common features from the sub class to the super class.
Refactoring for Visual Basic has a nice section on Extract Super Class that you might find interesting.
Be careful to not overuse inheritance. "Driver" strikes me as something that you really want to use composition for. A vehicle has a driver. Similarly other things such as the might be better handled using composition. For instance you could have a car that can go 200km/h, and have one that can go 300km/h. Really do not want to have different classes for that. You could have a simple int value or a EngineBehaviour class if you have something more complex. (Keyword: strategy pattern) Also be sure to not instantiate such composite objects in your object but rather inject them (keyword: dependency injection).

When to use Categories

I've recently discovered categories and was wondering when it might be appropriate to use them in a user defined class/new class. For example, I can see the benefits of adding a category to an existing class like NSString, but when creating a new class what would be the advantage of adding a category to this rather than just implementing a normal method?
Hope this makes sense.
Many thanks
Jules
The answer isn't really any different for your own classes than it is for framework classes. If you have multiple projects, you'll likely end up sharing some classes between them. However, you may want to extend some of your classes so that they work more easily with a specific project, but not want to include those extra methods in your other projects, where they might not make sense. You can use a category to extend your class without needing to subclass.
If I understand your question correctly, creating a "new class" is always "subclassing" because you're subclassing NSObject at the very least.
You could use categories on a new class to separate out sections of responsibility of a complex class. For example, all the basic functionality (instance variables, accessors, description, etc.) can go in one file (the "main" class file) while all methods to support a protocol (such as NSTableViewDataSource) can go in another.
Some take this approach to keep things "neat". I'm a firm believer in "if it's my own custom class, all its code should be in one file" so I do not personally do this. I demarcate different logical aspects of the class' code with "#pragma mark Some Section Name" to help navigation and readability. Your mileage may vary.
Adding a Category on NSString is useful when you want to call a method on every single NSString instance you will encounter. This is a real improvement over inheritance for this kind of object because they are used by the core framework and you don't have to convert a NSString object to your subclass when you want to call your custom method.
On the other hand, you can just put methods in, no instance variables.
In the book Refactoring by Martin Fowler, he has a section titled "Introduce Foreign Method" (A server class you are using needs an additional method, but you can't modify the class.) That's what categories are good for.
That said, there are times when using a category, instead of changing the class, is appropriate. A good example on using a category, even though you could change the server class, is how Apple handled the UIViewController MediaPlayer Additions. They could have put these two methods in UIViewController itself but since the only people who would ever use them are people who are using the Media Player framework, it made more sense to keep the methods there.