class inheritance in objective-c falls short in this case. is there any alternatives? - iphone

class AGImageVC
class AGVideoVC inherits from AGImageVC
class AGAdvancedImageVC inherits from AGImageVC
class AGAdvancedVideoVC inherits from ????
AGAdvancedVideoVC should have implementation from both AGAdvancedImageVC and AGVideoVC. But that's not possible...
I've also been thinking about category, but same problems would definitely be more obvious.

You need to think of class inheritance as a tree in Obj-C. Each class can have multiple sub-classes, but sub-classes can only have one parent. Objective-C lacks the concept of multiple inheritance as we traditionally understand it. People have found various ways to 'fake' multiple inheritance, which are discussed in the links below (personally, I wouldn't recommend them).
There is a fairly detailed explanation of your options regarding multiple inheritance on this Cocoa mailing list post from a few years back: http://www.cocoabuilder.com/archive/cocoa/131033-multiple-inheritance-and-objective.html
Another discussion on the subject here:
http://www.cocoadev.com/index.pl?MultipleInheritance

That's as close as you can get (using message forwarding) to behavior similar to multiple inheritance. This is not nice design in Objective-C, however. Flat inheritance hierarchies are more common in Objective-C.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtForwarding.html

That means that you have poorly designed architecture for this case. Try to rethink it and use another approach. Maybe you'd better want to use aggregation instead of inheritance. For example in some implementation AGVideo has to control video playback. Maybe it is implemented as the sequence of images. Then the solution would be to aggregate multiple AGImage instances and not inheriting from it.
If you want your class to implement functionality of different nature (e.g. both serialization and graphics rendering) the best choice would be using protocols. In this case each class would have it's own behavior for specified action but still you can manage the set of objects with different behavior but the same interface.

Related

Forms in Symfony 2: 'inherit_data' or class inheritance?

I need to make a bunch of forms in Symfony 2.8 using inheritance. I've seen two approaches being used:
Using 'regular' class inheritance like described in the first answer here.
Using inherit_data.
What's the difference between the two? Why would I pick one over the other?
Also, can I just make my 'base'-form type an abstract class, in order to prevent it from being used in its own? Are there any downsides to this?
Shortly speaking all needed info is already disclosed in links you posted.
Form inheritance is about real OOP class inheritance.
inherit_data is used for composition approach, so you can use it in forms, which are not really so bounded logically to be inherited from base class.
This implements composition over inheritance approach
https://en.m.wikipedia.org/wiki/Composition_over_inheritance

why can a class implement multiple interfaces?

This is the only question about interfaces in oop I can't seem to fully explain. So again, why in oop can a class implement multiple interfaces?
If you can provide a few examples that would be great. thanks in advance.
Conceptual Example
The way I think about the multiple interfaces is interface is like the verb or adjective, and class is like the subject.
A tiger can run, so the Tiger class may implement Runnable Interface.
A tiger can eat, so the Tiger class may implement Eatable Interface.
Because an instance of the class could have different behaviors, we could have different corresponding interfaces.
Realistic Example
java.util Class HashMap<K,V>
It implements Serializable, Cloneable, Map<K,V>
All of the interfaces are the characteristics of Class HashMap.
First thing is java doesn't support multiple inheritance hence you can not extend two classes at the same time. However, java support implementation of multiple interfaces. The example given by Mingyu seems perfect to me.
interfaces are essentially abstract(ofcourse not by definition, just saying) , therefore all methods have to be implemented in the concrete subclasses, in this way we avoid the deadly diamond of death, supporting multiple inheritance in a way which in itself is the answer for multiple interface implementation to be allowed.
there are many other uses too but due to the above explaination, there isnt any other reason to restrict the concept of multiple implementation....to the best of my knowledge.
Java class cannot extend multiple classes because of diamond ♦ problem. Diamond ♦ problem occurs due of constructor chaining.
Constructor is not present in Interface so no diamond ♦ problem will occur if we implement multiple interfaces. That's why Java class can implement multiple interfaces.

OOP: Is it normal to have a lot of inherited classes?

I started writing some code for a 2D game, created a class "objets" trying to keep it as generic as possible. I have a few methods and attributes that are common to every kind of element (buldings, ppl, interface buttons, etc) like (w, h, x, y ...you know) but most of them only make sense when applied to and specific type of item.
So I would have to inherit a new class for every type of actor in the game?
Just wondering if this is a common practice, or maybe i should manage it in a different way.
Thanks in advance.
If you're introducing behaviour then subclass, however if the difference is attribute based then don't e.g.
Animal (has .colour and .makeSound) -> Dog (has .eatOwnPoop) -> RedDog (no, too specific, covered by colour)
Notice how I had ".makeSound" in Animal. I could have put .bark in dog, but then I'd have to put .meow in cat etc. The subclass can simply override and provide a concrete sound.
However, you can use interfaces to better cross-cut your code, but that's quite a lengthy topic and probably overkill for your needs (although it could help any unit testing you do).
It sounds like you are over-using inheritance. It is certainly a red flag when you simultaneously say "common attributes like ..." and "...only make sense when applied to a specific type." Also, it is a red flag that domain objects such as building share a common base class with an interface object like button. Finally, it is quite unusual to define your own objet (object?) class from which every class in your system derives. It's not inconceivable, but in combination with your other comments, it sounds like you've started down an unproductive path.
You might want to refer to a good tutorial on object-oriented design and analysis such as "Head First OOA&D"
You do not HAVE to do anything. Generally, it is useful to use derived classes if they exhibit some kind of commonality but become more specialised in nature requiring specific functionality at each level of inheritance. It is also good to use if you want to have polymorphic behaviour. You have asked a very open ended question but basically do not feel that you HAVE to use inheritance as not every problem requires it and indeed some people overuse inheritance, introducing it in places where it really is not needed. All in all, I would really recommend that if you haven't already that you read a good book on object oriented design as this will then get you to think about your code from a different perspective and greatly improve the way you view software and design it. It may sound like a cop out but this kind of question is very hard to answer without knowing all details of what you are doing.

If you have Traits, do you stop using interfaces, Abstract base classes, and multiple inheritance?

It seems like Traits could completely replace interfaces, abstract base classes, mixins, and multiple inheritance, leaving you with just Traits and concrete inheritance.
Is this the intent?
If you have traits, which of the other code structuring constructs should you use?
(Roles are the Perl name for Traits.)
At least for Perl's Moose, there are no interfaces, so roles clearly subsume those, and generally mixins too. I'd say there still could be a case for abstract base classes. Roles can be considered what objects do, where classes are what they are.
By this line of reasoning, there still might be a valid use for an abstract base class. A URL is one example. There could easily be an abstract base class for a URL. An IO stream might be different, perhaps better as a role, as it defines how things behave rather than what they are.
When using roles, however, I have yet to see any clear need for true multiple inheritance from more than one class.
I have no use for interfaces or abstract classes at this point, but mixins and multiple inheritance are really enabled by traits so the usage of those paradigms is strongly encouraged here. Check the entire collection library to see the very rich classes you can build using these ideas.
Ah, my comments reflect Scala - I didn't realize you tagged this with multiple languages.
When you instanciate a trait; it consumes one classe.
So regardless of expressivity; You may still use legacy construct for preventing classes explosion in your jar (and starting time).
I let others answer about expressivity :)
I'm only talking about Scala here...
Read this.

How do you go from an abstract project description to actual code?

Maybe its because I've been coding around two semesters now, but the major stumbling block that I'm having at this point is converting the professor's project description and requirements to actual code. Since I'm currently in Algorithms 101, I basically do a bottom-up process, starting with a blank whiteboard and draw out the object and method interactions, then translate that into classes and code.
But now the prof has tossed interfaces and abstract classes into the mix. Intellectually, I can recognize how they work, but am stubbing my toes figuring out how to use these new tools with the current project (simulating a web server).
In my professors own words, mapping the abstract description to Java code is the real trick. So what steps are best used to go from English (or whatever your language is) to computer code? How do you decide where and when to create an interface, or use an abstract class?
So what steps are best used to go from English (or whatever your language is) to computer code?
Experience is what teaches you how to do this. If it's not coming naturally yet (and don't feel bad if it doesn't, because it takes a long time!), there are some questions you can ask yourself:
What are the main concepts of the system? How are they related to each other? If I was describing this to someone else, what words and phrases would I use? These thoughts will help you decide what classes are useful to think about.
What sorts of behaviors do these things have? Are there natural dependencies between them? (For example, a LineItem isn't relevant or meaningful without the context of an Order, nor is an Engine much use without a Car.) How do the behaviors affect the state of the other objects? Do they communicate with each other, and if so, in what way? These thoughts will help you develop the public interfaces of your classes.
That's just the tip of the iceberg, of course. For more about this thought process in general, see Eric Evans's excellent book, Domain-Driven Design.
How do you decide where and when to create an interface, or use an abstract class?
There's no hard and fast prescriptions; again, experience is the best guide here. That said, there's certainly some rules of thumb you can follow:
If several unrelated or significantly different object types all provide the same kind of functionality, use an interface. For example, if the Steerable interface has a Steer(Vector bearing) method, there may be lots of different things that can be steered: Boats, Airplanes, CargoShips, Cars, et cetera. These are completely unrelated things. But they all share the common interface of being able to be steered.
In general, try to favor an interface instead of an abstract base class. This way you can define a single implementation which implements N interfaces. In the case of Java, you can only have one abstract base class, so you're locked into a particular inheritance hierarchy once you say that a class inherits from another one.
Whenever you don't need implementation from a base class, definitely favor an interface over an abstract base class. This would also be handy if you're operating in a language where inheritance doesn't apply. For example, in C#, you can't have a struct inherit from a base class.
In general...
Read a lot of other people's code. Open source projects are great for that. Respect their licenses though.
You'll never get it perfect. It's an iterative process. Don't be discouraged if you don't get it right.
Practice. Practice. Practice.
Research often. Keep tackling more and more challenging projects / designs. Even if there are easy ones around.
There is no magic bullet, or algorithm for good design.
Nowadays I jump in with a design I believe is decent and work from that.
When the time is right I'll implement understanding the result will have to refactored ( rewritten ) sooner rather than later.
Give this project your best shot, keep an eye out for your mistakes and how things should've been done after you get back your results.
Keep doing this, and you'll be fine.
What you should really do is code from the top-down, not from the bottom-up. Write your main function as clearly and concisely as you can using APIs that you have not yet created as if they already existed. Then, you can implement those APIs in similar fashion, until you have functions that are only a few lines long. If you code from the bottom-up, you will likely create a whole lot of stuff that you don't actually need.
In terms of when to create an interface... pretty much everything should be an interface. When you use APIs that don't yet exist, assume that every concrete class is an implementation of some interface, and use a declared type that is indicative of that interface. Your inheritance should be done solely with interfaces. Only create concrete classes at the very bottom when you are providing an implementation. I would suggest avoiding abstract classes and just using delegation, although abstract classes are also reasonable when two different implementations differ only slightly and have several functions that have a common implementation. For example, if your interface allows one to iterate over elements and also provides a sum function, the sum function is a trivial to implement in terms of the iteration function, so that would be a reasonable use of an abstract class. An alternative would be to use the decorator pattern in that case.
You might also find the Google Techtalk "How to Design a Good API and Why it Matters" to be helpful in this regard. You might also be interested in reading some of my own software design observations.
Also, for the coming future, you can keep in pipeline to read the basics on domain driven design to align yourself to the real world scenarios - it gives a solid foundation for requirements mapping to the real classes.