object oriented design - oop

I recently started learning test-driven development but I always see myself changing the design of my class so that higher level class can access some more properties. (After changing design, my test cases will have to be rewritten too)
For example, I am practicing this by writing a MineSweeper program.
The MineFieldImp class has a width and a height property, but I didn't expose this in the MineField interface I created earlier. But later on I find out I need this features, so adding these properties requires me to add public methods to this class as well as the interface it's implementing.
I constantly see myself adding methods or fields to a class that I didn't think of earlier.
What am I doing wrong? What should I do to improve?
Thanks,
Yang

You aren't doing anything wrong. Class design is an constantly evolving process, its constantly changing. That's the beauty of TDD and unit testing. As your design changes you have your unit tests to assure you that your re-factoring hasn't broken anything.
I'd highly suggest reading Fowler's Refactoring book, there's lots of great information in there, including many useful refactoring patterns and guidance on how to refactor. It will definately help you be more productive and help you produce better object oriented designs.

Related

Why is inheritance So important, when you can Just create different classes and use them separately

I have been learning about Object-Oriented Programming. I am currently learning about inheritance but don't know where to apply it and use it. I really want to know about it because I strictly focus on the Application of different functionalities and how to use them.
Inheritance is incredibly useful for encapsulation. It promotes the reusability of code without rewriting the code and it is even helpful in decreasing the time complexity of the program which can be really advantageous in competitive coding.
Inheritance is mostly used to share functionality between kindred classes - that's even why the word for it is inheritance. Your child class inherits methods and fields of the parent class and therefore has access to the same functionality as the parent class.
The primary use case is to avoid code duplication or to make the design of complex objects a bit easier - but this is already well covered and doesn't need another elaboration.
But in the end, software architecture and design is always something which is subject to opinions - there may be best practices which really make sense to adhere to but on the other hand: You don't always have the time to design and code clean software.

"Huge class files are bad" — is it really and what is the best solution?

In a code review, I heard it is bad to create huge classes with a lot lines of code. Apparently the 1000 rules of code I had was terrible practice in terms of readability/navigability, I do hear some sense in that.
So I have some complex classes which are basically the code logic behind different screens. I'm programming on Android so this is for example for a Fragment or Activity (though this is a generic question).
Now I can choose to group methods and put them in Utility classes. This will at the very least shorten my code in the sense of lines per class and put some feeling about what method is where. The methods though, are really only used by no more than 1 class, so should this really be a utility class? My gut feeling says utility classes should be stateless classes that contain static methods usable for classes.
Now I could also go for collapsible code blocks and group my methods in them. This will provide readability and usability for me, but not for other programmers.
Then if I look at for instance the Android Activity class, it contains over 6000 lines of code. Is this considered bad practice as well?
I realize this question might be too much "opinion based" but I hope there is a clear and common answer to it.
Lines of code is a somewhat meaningless measure in my opinion. Certain types of classes are going to be naturally longer - for example MVC controllers.
The most important principal to keep in mind when designing a class is the single responsibility principle, which states:
every class should have a single responsibility, and that
responsibility should be entirely encapsulated by the class
The Activity type in Android could well follow this principal and still be 6000 lines long if, for example, an activity is a very complex thing which requires lots of horrible nested control and flow statements.
Without seeing the class it's difficult to say, however, in practice, it's unlikely that a well designed single class would grow to this size.

Design classes - OOPS features

I am interested in improving my designing capability (designing of classes with its properties, methods etc) for a given.
i.e. How to decide what should be the classes, methods and properties?
Can you guys suggest me good material for improving on this?
Please see:
Any source of good object-oriented design practises?
Best Resources to learn OO Design and Analysis
among many....
Encapsulation: The wrapping up of data and functions into a single unit is known as encapsulation. Or, simply put: putting the data and methods together in a single unit may be a class.
Inheritance: Aquiring the properties from parent class to child class. Or: getting the properties from super class to sub class is known as inheritance.
Polymorphism: The ability to take more that one form, it supports method overloading and method overriding.
Method overloading: When a method in a class having the same method name with different arguments (diff parameters or signatures) is said to be method overloading. This is compile-time polymorphism – using one identifier to refer to multiple items in the same scope.
This is perhaps a question which every programmer thinks of one day.
The designing capability comes with your experience gradually. What I would say is in general scenario if you can visualize the Database objects for a given problem, the rest is a cakewalk (isnt true sometimes if you work on a techie project with no DB)
You can start thinking of objects which are interacting in the real world to complete the process and then map them to classes with appropriate properties and then methods for defining their behavior. Ten you can focus on the classes which contribute to running the workflow and not to any individual real world object.
This gets a lot simplified if we focus on designing the DB before we jump directly to code design.
A lot depends on the pattern you choose - If you see a problem from MVC perspective, you will naturally be drawn towards identifying "controller" classe first and so on.
I guess I need not repeat the golden sources of design and OOPS wisdom - they already posted here or there.
I would recommend you to read up on some UML and design patterns. That gets you going with the thinking in "drawing" terms. You can also get a good grasp of a big class/object a lot easier.
One particular book that is good in this area.
Applying UML and Patterns
Give a look a Domain-Driven Design, which defines entities, value objects, factories, services and repositories and the GRASP patterns (General Responsibility Assignment Software Patterns) e.g. Expert, Creator, Controller.
Have a look at the part 1 screencast the first part is not silverlight but just a command line calculator that starts out as a single bit of code, and is then broken down into classes.

Learning object oriented thinking [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm currently working on a small 2D game-engine in C++, but I am now facing a daemon - I suck at designing a 'system of classes' that actually works. There are a blockade in my mind that disables me from seeing where I should use a class and where I should not. I was reading an article about engine-design and it purposed to use a 'State' class to manage the state of different game entries (I was using an int).
It also suggested that all objects for the game (not io/video/sound etc) derive from either Renderable or NonRenderable classes. That's smart. I already know that that was a smart way of doing it - I mean, every object in Java is of baseclass Object right? Smart, I know that! How come I didn't do it that way? What do I have to read to really get into this mindset?
Another example. I'm taking this summer-course in Ruby (really simple) and we're supposed to design a camping site. Simple! So, a camping is a collection of 'plots' that each have a electrical-gauge to measure how much power the guest has consumed. My design was three classes, one for a Camping - that in turn used arrays of Guest and Plot classes. My teacher suggested that I use more classes. WTF(!) was my first thought, where, what classes? Everything was a class in my opinion - until I realized, maybe the gauge should be a class to? Right now the gauge was an Integer in the Plot class.
I want to learn how to come up with a object oriented solutions to my problems - not just how to make the most obvious stuff into classes!
Tips/books/articles/blogs?
I'm two years into a collage degree in CS and have been programming as a hobby for many years! I'm 'just' stuck - and it's preventing me from creating any larger piece of software!
My personal experience was learning Object Oriented Software Construction with Object Oriented Software Construction, 2nd Edition by Bertrand Meyer.
The book was invaluable to me at that time, and still remains the single book from which I've learnt most regarding OO programming and software construction in general.
Here are some of its strong points:
In Part A: The issues, a very good definition of software quality.
In Part B: The road to object orientation, a logical, step by step search for OO techniques in a way that makes the reader think the investigation is being done live, that is, as if there were still no known results. You'll probably acquire the mindset you're looking for from this part.
In Part C: Object oriented techniques, the technical core of the book, you'll make your knowledge solid and learn very useful techniques regarding Design by Contract, Inheritance, Genericity, etc.
Part D: OO methodology: Applying the method well is a more practical approach on design, which I also find very useful. See for example How to find the classes (22), which you can find online.
After these parts, more advanced topics come, such as Concurrency (30) or Databases (31).
Since the book uses the Eiffel language (designed by the author), this will put you in the right mindset and teach you to think. It will be easy to apply these ideas to other, more or less OO, programming languages.
Object-oriented
Object-oriented programming is about asking objects to do something: a deceptively difficult concept to correctly apply.
Goban
Consider a 2D game board, like for playing Go (called a goban).
Think first about the behaviour it requires to accomplish its task. This means listing the behaviour for an object rather than deciding on data the behaviours manipulate. For example a basic board might have the following behaviours:
Place a Go stone.
Remove a Go stone.
Remove all the stones.
For a computer version of Go, it is convenient to bring attention to specific areas:
Mark an intersection (e.g., triangle, number, letter, circle, square).
Remove a mark from a marked intersection.
Remove all the marks.
Notice that a goban does not need to provide a way to provide clients with a reference to the stone at a specific intersection. Instead, it can answer questions about its state. For example, a goban might answer the following questions:
Is there a black stone at a given intersection?
Is there a white stone at a given intersection?
Is there a mark at a given intersection?
It is not the responsibility of the goban to know the state of the game: that belongs to an instance of a Game (which has Rules). In real life, a goban is simply a stage for stones.
At this point, we could write an interface for a goban without knowing how the underlying implementation will work.
public interface Goban {
public void place( Stone stone, Point point );
public void removeStone( Point point );
public void removeStones();
public void place( Mark mark, Point point );
public void removeMark( Point point );
public void removeMarks();
public boolean hasWhiteStone( Point point );
public boolean hasBlackStone( Point point );
public boolean hasMark( Point point );
}
Notice how the board is cleanly separated from both Rules and Games. This makes the goban reusable for other games (involving stones and intersections). The goban could inherit from a generic interface (e.g., a Board interface), but this should suffice to explain one way to think in terms of objects.
Encapsulation
An implementation of the Goban interface does not expose its internal data. At this point, I could ask you to implement this interface, write unit tests, and send me the compiled class when you have finished.
I do not need to know what data structures you have used. I can use your implementation to play on (and depict) a Goban. This is a crucial point that many projects get wrong. Many, many projects code the following:
public class Person {
private HairColour hairColour = new HairColour( Colour.BROWN );
public Person() {
}
public HairColour getHairColour() {
return hairColour;
}
public void setHairColour( HairColour hairColour ) {
this.hairColour = hairColour;
}
}
This is ineffective encapsulation. Consider the case where Bob does not like to have his hair coloured pink. We can do the following:
public class HairTrickster {
public static void main( String args[] ) {
Person bob = new Person();
HairColour hc = bob.getHairColour();
hc.dye( Colour.PINK );
}
}
Bob has now had his hair coloured pink, and nothing could prevent it. There are ways to avoid this situation, but people do not do them. Instead, encapsulation is broken resulting in rigid, inflexible, bug-ridden, and unmaintainable systems.
One possible way to enforce encapsulation is by returning a clone of HairColour. The revised Person class now makes it difficult to change the hair colour to Pink.
public class Person {
private HairColour hairColour = new HairColour( Colour.BROWN );
public Person() {
}
public HairColour getHairColour() {
return hairColour.clone();
}
public void setHairColour( HairColour hairColour ) {
if( !hairColour.equals( Colour.PINK ) {
this.hairColour = hairColour;
}
}
}
Bob can sleep soundly, knowing he will not awake to a pink dye job.
It pays to remember: OO is not an end in itself. The point of OO is to make development and, especially, maintenance of code easier over the lifetime of the product. Beware of the "OO for OO's sake" mindset.
Head First Object-Oriented Analysis and Design
I love Head First Books because they are fun to read. They have exercises and puzzles to scratch your head. I've read this book and found it very good.
The book covers:
Use OO principles (encapsulation and delegation)
Open-Closed Principle (OCP)
The Single Responsibility Principle (SRP)
Design patterns, UML, Use cases etc.
There are a blockade in my mind that disables me from seeing where I should use a class and where I should not.
When it comes down to it classes are a way to separate complex systems into simple parts that interact with each other. Try to create classes where otherwise you would be repeating yourself.
Right now the gauge was an Integer in the Plot class.
Does the gauge need to be a class? What would the advantage of turning it into a class be? These are the sort of things you always need to ask yourself.
Game Engines are difficult to design. The separation of such a vaguely defined requirements is a complex process, read here: article on game engines
Design is iterative and you'll refactor several times, don't be surprised by this.
There's an essay in the book "ThoughtWorks Anthology" by Jeff Bay: "Object Calisthenics" in which he gives a set of rules for designing OOP sofware:
Use only one level of indentation per method
Don't use the else keyword
Wrap all primitives and strings
Use only one dot per line
Don't abbreviate
Keep all entities small
Don't use any classes with more than two instance variables
Use first-class collections
Don't use any getters/setters/properties
On the first look it may look too strict to follow all these rules. Keep in mind that even trying to write some code that coplies them will make you better OOP designer.
Just remember there is never 1 solution to a problem.
Turning everything into a class is also not the solution. Especially tiny things (like the gauge) might very well be an int or float member inside the plot class like you had.
My suggestion is that practice is a good teacher. Just keep on trying, and keep on reading. In time you'll be more and more fluent.
I probably learned most about object oriented software development from Craig Larman´s Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development.
In his approach, classes are derived in a systematic way from use cases:
Nouns in the use cases are mapped to classes,
verbs to methods and
adjectives to member variables.
This, of course, works better for notions in the problem domain than, say, GUI widgets. Nevertheless, starting with a description/use case of the program to be written helped me to find better abstractions than when I omitted that step.
For me OO didn't 'click' until I read a book about design patterns. If you're already comfortable with concepts like abstract classes, interfaces, etc that's only half the battle.
The next step is figuring out why you should prefer composition over inheritance, how to code to an interface and how to write your classes so that they are decoupled and well-encapsulated. Design patterns show you solutions to common OO problems and help you structure your code adhering to the above guidelines.
I can't recommend any particular books about C++ but the GOF book is the standard on Design Patterns (Java). I prefer books that talk about design patterns in a particular language so that you can get concrete code examples. Design Patterns In Ruby is pretty good, as is PHP: Objects, Patterns and Practice.
I get the feeling that your instructor doesn't particularly know what he's talking about. 'More classes' is pretty useless advice by itself.
One of the things which helped to get into OO mindset, along with the practices that earlier posts outlined has been, is to rewrite/improving the existing code you have written using OO principles.
For example :
a. In situations where there is a lot of if/else constructs then probably
you can think of having a class hierarchy to distribute the branch codes accordingly,
and to use polymorphism.
b. Any use of operators like (instanceof in Java) would indicate programming to
concrete types and you can think how the instanceof check can be get rid of.
c. Use "Law of Demeter" as a guideline and see whether the coupling between
classes is high
To an extent the practice of "Test Driven Development" also helped me
since it forces you to think in terms of interfaces/behavior to be exposed
by a class rather than just concentrating on how best solution to a problem
can be coded.
Maybe you will find Thinking in patterns by Bruce Eckel useful. You can download this book from his site for free (I can only post one link as a new member, so just click on the links there and you can find it). Although, the book is from 2003, maybe the ideas presented in this book will help you grow as a programmer in general.
Write a really huge piece of software, and throughout the process, the bigger it gets, the more extensiblity you'll need and the more good class design you'll need, thus next time you'll think ahead and make your class design good in the beginning...
A simple way to come up with a reasonable set of things which probably should be objects (and hence, classes): write down a problem description of your task, like:
On a camping site there are guests, and each guest has access to a few outlets. The
software should be able to manage the power consumed by each guest, so it should know the
outlets used by a guest and the power consumed through each outlet.
Now, create a list of all the nouns for a good idea of what classes (= kind of objects) are involved in your problem:
Camping Site
Guest
Outlet
Power
This is not necessarily a definitive list, but it's a good start.
Haha. I remember that point. The whole "how the hell does this oo thing work?". Just keep at it, at some point it just clicks. It really is like a lightbulb going on. One moment it doesn't really make sense and then a split second later you're coding everything up in classes.
Try downloading some of the open source tools you will likely end up using and read the code. It'll give you something to reference your code style against.
Peter Coad and Ed Yourdon wrote a book about it couple years ago. While not filled with new overhyped methdologies, this book provides good foundation for thinking in object style.
In my opinion, one of the the best books I've read for learning object oriented concepts is:
The Object-Oriented Thought Process
For me, this book really gets you thinking in an object oriented way (well, the clue's in the title! :) It's fairly language agnostic, containing some small code samples throughout the text in VB.NET, C# and Java and frequently references many "greats" in the world of OO analysis and design, like Grady Booch, Martin Fowler and others.
Since the book helps you to think in an object oriented way, it'll often take a specific example and show the differences between the OO way of approaching a problem and the procedural way. This can be a big help if you're coming from more or a procedural background. It also touches on things like UML to help explain and understand the design behind complete libraries of classes (e.g. frameworks) and the interaction between classes and also the design of rich class hierarchies using concepts such as aggregation and composition.

Is Inheritance really needed?

I must confess I'm somewhat of an OOP skeptic. Bad pedagogical and laboral experiences with object orientation didn't help. So I converted into a fervent believer in Visual Basic (the classic one!).
Then one day I found out C++ had changed and now had the STL and templates. I really liked that! Made the language useful. Then another day MS decided to apply facial surgery to VB, and I really hated the end result for the gratuitous changes (using "end while" instead of "wend" will make me into a better developer? Why not drop "next" for "end for", too? Why force the getter alongside the setter? Etc.) plus so much Java features which I found useless (inheritance, for instance, and the concept of a hierarchical framework).
And now, several years afterwards, I find myself asking this philosophical question: Is inheritance really needed?
The gang-of-four say we should favor object composition over inheritance. And after thinking of it, I cannot find something you can do with inheritance you cannot do with object aggregation plus interfaces. So I'm wondering, why do we even have it in the first place?
Any ideas? I'd love to see an example of where inheritance would be definitely needed, or where using inheritance instead of composition+interfaces can lead to a simpler and easier to modify design. In former jobs I've found if you need to change the base class, you need to modify also almost all the derived classes for they depended on the behaviour of parent. And if you make the base class' methods virtual... then not much code sharing takes place :(
Else, when I finally create my own programming language (a long unfulfilled desire I've found most developers share), I'd see no point in adding inheritance to it...
Really really short answer: No. Inheritance is not needed because only byte code is truly needed. But obviously, byte code or assemble is not a practically way to write your program. OOP is not the only paradigm for programming. But, I digress.
I went to college for computer science in the early 2000s when inheritance (is a), compositions (has a), and interfaces (does a) were taught on an equal footing. Because of this, I use very little inheritance because it is often suited better by composition. This was stressed because many of the professors had seen bad code (along with what you have described) because of abuse of inheritance.
Regardless of creating a language with or without inheritances, can you create a programming language which prevents bad habits and bad design decisions?
I think asking for situations where inheritance is really needed is missing the point a bit. You can fake inheritance by using an interface and some composition. This doesnt mean inheritance is useless. You can do anything you did in VB6 in assembly code with some extra typing, that doesn't mean VB6 was useless.
I usually just start using an interface. Sometimes I notice I actually want to inherit behaviour. That usually means I need a base class. It's that simple.
Inheritance defines an "Is-A" relationship.
class Point( object ):
# some set of features: attributes, methods, etc.
class PointWithMass( Point ):
# An additional feature: mass.
Above, I've used inheritance to formally declare that PointWithMass is a Point.
There are several ways to handle object P1 being a PointWithMass as well as Point. Here are two.
Have a reference from PointWithMass object p1 to some Point object p1-friend. The p1-friend has the Point attributes. When p1 needs to engage in Point-like behavior, it needs to delegate the work to its friend.
Rely on language inheritance to assure that all features of Point are also applicable to my PointWithMass object, p1. When p1 needs to engage in Point-like behavior, it already is a Point object and can just do what needs to be done.
I'd rather not manage the extra objects floating around to assure that all superclass features are part of a subclass object. I'd rather have inheritance to be sure that each subclass is an instance of it's own class, plus is an instance of all superclasses, too.
Edit.
For statically-typed languages, there's a bonus. When I rely on the language to handle this, a PointWithMass can be used anywhere a Point was expected.
For really obscure abuse of inheritance, read about C++'s strange "composition through private inheritance" quagmire. See Any sensible examples of creating inheritance without creating subtyping relations? for some further discussion on this. It conflates inheritance and composition; it doesn't seem to add clarity or precision to the resulting code; it only applies to C++.
The GoF (and many others) recommend that you only favor composition over inheritance. If you have a class with a very large API, and you only want to add a very small number of methods to it, leaving the base implementation alone, I would find it inappropriate to use composition. You'd have to re-implement all of the public methods of the encapsulated class to just return their value. This is a waste of time (programmer and CPU) when you can just inherit all of this behavior, and spend your time concentrating on new methods.
So, to answer your question, no you don't absolutely need inheritance. There are, however, many situations where it's the right design choice.
The problem with inheritance is that it conflates the issue of sub-typing (asserting an is-a relationship) and code reuse (e.g., private inheritance is for reuse only).
So, no it's an overloaded word that we don't need. I'd prefer sub-typing (using the 'implements' keyword) and import (kinda like Ruby does it in class definitions)
Inheritance lets me push off a whole bunch of bookkeeping onto the compiler because it gives me polymorphic behavior for object hierarchies that I would otherwise have to create and maintain myself. Regardless of how good a silver bullet OOP is, there will always be instances where you want to employ a certain type of behavior because it just makes sense to do. And ultimately, that's the point of OOP: it makes a certain class of problems much easier to solve.
The downsides of composition is that it may disguise the relatedness of elements and it may be harder for others to understand. With,say, a 2D Point class and the desire to extend it to higher dimensions, you would presumably have to add (at least) Z getter/setter, modify getDistance(), and maybe add a getVolume() method. So you have the Objects 101 elements: related state and behavior.
A developer with a compositional mindset would presumably have defined a getDistance(x, y) -> double method and would now define a getDistance(x, y, z) -> double method. Or, thinking generally, they might define a getDistance(lambdaGeneratingACoordinateForEveryAxis()) -> double method. Then they would probably write createTwoDimensionalPoint() and createThreeDimensionalPoint() factory methods (or perhaps createNDimensionalPoint(n) ) that would stitch together the various state and behavior.
A developer with an OO mindset would use inheritance. Same amount of complexity in the implementation of domain characteristics, less complexity in terms of initializing the object (constructor takes care of it vs. a Factory method), but not as flexible in terms of what can be initialized.
Now think about it from a comprehensibility / readability standpoint. To understand the composition, one has a large number of functions that are composed programmatically inside another function. So there's little in terms of static code 'structure' (files and keywords and so forth) that makes the relatedness of Z and distance() jump out. In the OO world, you have a great big flashing red light telling you the hierarchy. Additionally, you have an essentially universal vocabulary to discuss structure, widely known graphical notations, a natural hierarchy (at least for single inheritance), etc.
Now, on the other hand, a well-named and constructed Factory method will often make explicit more of the sometimes-obscure relationships between state and behavior, since a compositional mindset facilitates functional code (that is, code that passes state via parameters, not via this ).
In a professional environment with experienced developers, the flexibility of composition generally trumps its more abstract nature. However, one should never discount the importance of comprehensibility, especially in teams that have varying degrees of experience and/or high levels of turnover.
Inheritance is an implementation decision. Interfaces almost always represent a better design, and should usually be used in an external API.
Why write a lot of boilerplate code forwarding method calls to a composed member object when the compiler will do it for you with inheritance?
This answer to another question summarises my thinking pretty well.
Does anyone else remember all of the OO-purists going ballistic over the COM implementation of "containment" instead of "inheritance?" It achieved essentially the same thing, but with a different kind of implementation. This reminds me of your question.
I strictly try to avoid religious wars in software development. ("vi" OR "emacs" ... when everybody knows its "vi"!) I think they are a sign of small minds. Comp Sci Professors can afford to sit around and debate these things. I'm working in the real world and could care less. All of this stuff are simply attempts at giving useful solutions to real problems. If they work, people will use them. The fact that OO languages and tools have been commercially available on a wide scale for going on 20 years is a pretty good bet that they are useful to a lot of people.
There are a lot of features in a programming language that are not really needed. But they are there for a variety of reasons that all basically boil down to reusability and maintainability.
All a business cares about is producing (quality of course) cheaply and quickly.
As a developer you help do this is by becoming more efficient and productive. So you need to make sure the code you write is easily reusable and maintainable.
And, among other things, this is what inheritance gives you - the ability to reuse without reinventing the wheel, as well as the ability to easily maintain your base object without having to perform maintenance on all similar objects.
There's lots of useful usages of inheritance, and probably just as many which are less useful. One of the useful ones is the stream class.
You have a method that should be able stream data. By using the stream base class as input to the method you ensure that your method can be used to write to many kinds of streams without change. To the file system, over the network, with compression, etc.
No.
for me, OOP is mostly about encapsulation of state and behavior and polymorphism.
and that is. but if you want static type checking, you'll need some way to group different types, so the compiler can check while still allowing you to use new types in place of another, related type. creating a hierarchy of types lets you use the same concept (classes) for types and for groups of types, so it's the most widely used form.
but there are other ways, i think the most general would be duck typing, and closely related, prototype-based OOP (which isn't inheritance in fact, but it's usually called prototype-based inheritance).
Depends on your definition of "needed". No, there is nothing that is impossible to do without inheritance, although the alternative may require more verbose code, or a major rewrite of your application.
But there are definitely cases where inheritance is useful. As you say, composition plus interfaces together cover almost all cases, but what if I want to supply a default behavior? An interface can't do that. A base class can. Sometimes, what you want to do is really just override individual methods. Not reimplement the class from scratch (as with an interface), but just change one aspect of it. or you may not want all members of the class to be overridable. Perhaps you have only one or two member methods you want the user to override, and the rest, which calls these (and performs validation and other important tasks before and after the user-overridden methods) are specified once and for all in the base class, and can not be overridden.
Inheritance is often used as a crutch by people who are too obsessed with Java's narrow definition of (and obsession with) OOP though, and in most cases I agree, it's the wrong solution, as if the deeper your class hierarchy, the better your software.
Inheritance is a good thing when the subclass really is the same kind of object as the superclass. E.g. if you're implementing the Active Record pattern, you're attempting to map a class to a table in the database, and instances of the class to a row in the database. Consequently, it is highly likely that your Active Record classes will share a common interface and implementation of methods like: what is the primary key, whether the current instance is persisted, saving the current instance, validating the current instance, executing callbacks upon validation and/or saving, deleting the current instance, running a SQL query, returning the name of the table that the class maps to, etc.
It also seems from how you phrase your question that you're assuming that inheritance is single but not multiple. If we need multiple inheritance, then we have to use interfaces plus composition to pull off the job. To put a fine point about it, Java assumes that implementation inheritance is singular and interface inheritance can be multiple. One need not go this route. E.g. C++ and Ruby permit multiple inheritance for your implementation and your interface. That said, one should use multiple inheritance with caution (i.e. keep your abstract classes virtual and/or stateless).
That said, as you note, there are too many real-life class hierarchies where the subclasses inherit from the superclass out of convenience rather than bearing a true is-a relationship. So it's unsurprising that a change in the superclass will have side-effects on the subclasses.
Not needed, but usefull.
Each language has got its own methods to write less code. OOP sometimes gets convoluted, but I think that is the responsability of the developers, the OOP platform is usefull and sharp when it is well used.
I agree with everyone else about the necessary/useful distinction.
The reason I like OOP is because it lets me write code that's cleaner and more logically organized. One of the biggest benefits comes from the ability to "factor-up" logic that's common to a number of classes. I could give you concrete examples where OOP has seriously reduced the complexity of my code, but that would be boring for you.
Suffice it to say, I heart OOP.
Absolutely needed? no,
But think of lamps. You can create a new lamp from scratch each time you make one, or you can take properties from the original lamp and make all sorts of new styles of lamp that have the same properties as the original, each with their own style.
Or you can make a new lamp from scratch or tell people to look at it a certain way to see the light, or , or, or
Not required, but nice :)
Thanks to all for your answers. I maintain my position that, strictly speaking, inheritance isn't needed, though I believe I found a new appreciation for this feature.
Something else: In my job experience, I have found inheritance leads to simpler, clearer designs when it's brought in late in the project, after it's noticed a lot of the classes have much commonality and you create a base class. In projects where a grand-schema was created from the very beginning, with a lot of classes in an inheritance hierarchy, refactoring is usually painful and dificult.
Seeing some answers mentioning something similar makes me wonder if this might not be exactly how inheritance's supposed to be used: ex post facto. Reminds me of Stepanov's quote: "you don't start with axioms, you end up with axioms after you have a bunch of related proofs". He's a mathematician, so he ought to know something.
The biggest problem with interfaces is that they cannot be changed. Make an interface public, then change it (add a new method to it) and break million applications all around the world, because they have implemented your interface, but not the new method. The app may not even start, a VM may refuse to load it.
Use a base class (not abstract) other programmers can inherit from (and override methods as needed); then add a method to it. Every app using your class will still work, this method just won't be overridden by anyone, but since you provide a base implementation, this one will be used and it may work just fine for all subclasses of your class... it may also cause strange behavior because sometimes overriding it would have been necessary, okay, might be the case, but at least all those million apps in the world will still start up!
I rather have my Java application still running after updating the JDK from 1.6 to 1.7 with some minor bugs (that can be fixed over time) than not having it running it at all (forcing an immediate fix or it will be useless to people).
//I found this QA very useful. Many have answered this right. But i wanted to add...
1: Ability to define abstract interface - E.g., for plugin developers. Of course, you can use function pointers, but this is better and simpler.
2: Inheritance helps model types very close to their actual relationships. Sometimes a lot of errors get caught at compile time, because you have the right type hierarchy. For instance, shape <-- triangle (lets say there is a lot of code to be reused). You might want to compose triangle with a shape object, but shape is an incomplete type. Inserting dummy implementations like double getArea() {return -1;} will do, but you are opening up room for error. That return -1 can get executed some day!
3: void func(B* b); ... func(new D()); Implicit type conversion gives a great notational convenience since Derived is Base. I remember having read Straustrup saying that he wanted to make classes first class citizens just like fundamental data types (hence overloading operators etc). Implicit conversion from Derived to Base, behaves just like an implicit conversion from a data type to broader compatible one (short to int).
Inheritance and Composition have their own pros and cons.
Refer to this related SE question on pros of inheritance and cons of composition.
Prefer composition over inheritance?
Have a look at the example in this documentation link:
The example shows different use cases of overriding by using inheritance as a mean to achieve polymorphism.
In the following, inheritance is used to present a particular property for all of several specific incarnations of the same type thing. In this case, the GeneralPresenation has a properties that are relevant to all "presentation" (the data passed to an MVC view). The Master Page is the only thing using it and expects a GeneralPresentation, though the specific views expect more info, tailored to their needs.
public abstract class GeneralPresentation
{
public GeneralPresentation()
{
MenuPages = new List<Page>();
}
public IEnumerable<Page> MenuPages { get; set; }
public string Title { get; set; }
}
public class IndexPresentation : GeneralPresentation
{
public IndexPresentation() { IndexPage = new Page(); }
public Page IndexPage { get; set; }
}
public class InsertPresentation : GeneralPresentation
{
public InsertPresentation() {
InsertPage = new Page();
ValidationInfo = new PageValidationInfo();
}
public PageValidationInfo ValidationInfo { get; set; }
public Page InsertPage { get; set; }
}