Inheritance is a bad practice for all languages?

12

I did a Java project architecture course and the instructor told me that Java inheritance is considered a bad practice, which should always be avoided and it is preferable if possible to use composition instead.

Is this valid for all other languages or just for Java?

Is this true for multiple inheritance too?

    
asked by anonymous 23.12.2016 / 13:06

1 answer

25

It is bad practice to teach things like bad practice or good practice.

The ideal would be to explain why things. Often the person does not explain why she does not know (I'm not saying that's the case). It is common for people to learn cake recipes. It reads somewhere and goes on to repeat that as absolute truth without questioning, without understanding why to use.

This is a problem of object orientation and not of Java, therefore inherent in all languages that adopt OOP. Curiously, the most striking feature of "paradigm" does not work as well as people imagined and only in some cases does it really is helpful. It often causes more problems than it generates.

If you want to use this term that I do not like, yes, it is bad practice as long as you understand that "practice" is something general that usually has many exceptions. If used correctly, where it is useful, no problem. If you think that being "bad practice" you should not use, then you are doing it wrong. You have to learn where to use it and where to avoid it. It is a "bad practice" to abuse the resource where it is not needed and has a better solution (composition and derivatives).

You have a few questions here that help you understand this:

Multiple inheritance

Multiple inheritance is another problem that aggravates the difficulty. So few language allow.

Imagine how complicated an object is to be two things at once. This can occur in biology problems. Even in chemistry things are made up of others and are not other things at the same time.

In addition to the conceptual problem, there are technical problems. It is difficult to implement a compiler that does this right and will require the language to have ways to resolve certain conflicts that may arise when you inherit from two different entities that may have states or behaviors with the same name. Having a name conflict is the least of the problems, as the conceptual conflict is more important.

One of the biggest problems is the diamond problem . Where two classes ( B and C ) inherit from a third ( A ). There a fourth (% with%) inherits from these two classes ( D and B ). Both had the same states and behaviors as C . Which of the two will be used in A ?

The way to access these members becomes complex and probably less performative than expected.

So multiple inheritance should be greatly avoided.

Some more modern languages are avoiding inheritance, although this will bring some difficulties for a few scenarios where the inheritance works very well.

    
23.12.2016 / 13:18