Advantages and disadvantages of inheritance and combination

Source: Internet
Author: User

Combination and inheritance are both ways to improve code reusability. When designing an object model, you can identify the combination and inheritance relationships between classes according to semantics. In some cases, a combination or inheritance relationship can accomplish the same task. There is a correspondence between the combination and inheritance: The overall class in the combination corresponds to the subclass in the inheritance, the local class in the combination corresponds to the parent class in the inheritance, for example:

Combination:

Inheritance:

I. Basic Knowledge

We first use the code to help you understand the combination and inheritance:

1. When a parent class already exists and its method needs to be extended

Structure:

Inheritance code:

class Parent    {        public void Method1()         {         }        public void Method2() { }        public void Method3() { }    } class Child1:Parent    {        public void MethodA() { }    } class Child2:Parent    {        public void MethodA() { }    }

Combined Code:

class ComponentA    {        Parent p = new Parent();        public void Method2()        {            p.Method2();        }        public void MethodA()        {        }    } class ComponentB    {        Parent p = new Parent();        public void Method2() {            p.Method2();        }        public void MethodB()        {         }    }

2. If two classes have many classes with the same code that need to be abstracted, for example, A and B, the method code of Method1 and method3 are the same in both classes.

Inheritance:

Implementation Code:

class A:C    {        public void MethodB() { }        public override void Method2()        {                    }    }    class B:C    {        public override void Method2()        {                    }        public void MethodB() { }    }    class C    {        public void Method1() { }        public virtual void Method2() { }        public void Method3() { }    }

Combination:

class A    {        public void MethodA() { }        C c = new C();        public void Method1()        {            c.Method1();        }        public void Method2() { }    }    class B    {        public void MethodB() { }        public void Method2() { }    }    class C    {        public void Method1() { }        public void Method2() { }        public void Method3() { }    }

Ii. Advantages and Disadvantages of inheritance and combination

Combination System

Follow-up

Advantage: No encapsulation is damaged. The overall class and local class are loosely coupled and independent from each other.

Disadvantage: destroys encapsulation. Child classes are closely coupled with parent classes. Child classes depend on the implementation of parent classes, and child classes lack independence.

Advantage: good scalability

Disadvantage: expansion is supported, but it is often at the cost of increasing the complexity of the system structure.

Advantage: dynamic combination is supported. During running, you can select different types of local objects for the entire object.

Disadvantage: Dynamic inheritance is not supported. Different parent classes cannot be selected for subclass during runtime.

Advantage: The overall class can be used to package Department classes, encapsulate local class interfaces, and provide new interfaces.

Disadvantage: The subclass cannot change the interface of the parent class.

Disadvantage: The overall class cannot automatically obtain the same interface as the Department class

Advantage: subclass can automatically inherit the interface of the parent class

Disadvantage: when creating an object of the overall class, you need to create objects of all local classes.

Advantage: when creating a subclass object, you do not need to create a parent class Object

1. Why inheritance destroys encapsulation:

The duck does not want the "Flying" method, but the inheritance cannot encapsulate this useless "Flying" method.

2. Why inherit tight coupling:

As the basetable of the parent class, the insert name is not suitable. If you want to change it to the create method, the insert method of the subclass object will cause compilation errors, you may think this is quite easy to change, because there is a refactoring tool, and compilation errors are easy to change. However, if the basetable and sub-classes are in different programming sets and the maintenance personnel are different, the basetable assembly is upgraded, and the originally usable code is suddenly unavailable, which is still unacceptable.

3. Why Is Inheritance and expansion complicated?

When the tax calculation method for books and digital products is the same as that for digital products, and the tax calculation method for consumer products is the same, if the inheritance scheme is adopted, it may become the following method:

In this way, if the product continues to increase and the tax calculation method continues to increase, the hierarchy of inheritance will be very complex and difficult to control, and the combination can effectively solve this problem. See: object-oriented brainstorm (1)

4. Inheritance cannot support dynamic inheritance

This is actually quite understandable, because inheritance is determined during the compilation period and cannot be changed during runtime. For example, in the three examples, if the user needs to select a tax calculation method based on local conditions, using inheritance cannot be solved, but using combination and reflection can be a good solution.

5. why can't the inherited subclass change the parent class interface?

As shown in figure 2

In the subclass, the insert method is not suitable and you want to use the Create method. It cannot be changed because of inheritance.

 

Iii. How to Use inheritance

1. Well-designed classes specially designed for inheritance. The abstract layer of the inheritance tree should be relatively stable, generally not more than three layers.

2. For classes not specifically used for inheritance, do not inherit them.

3. Use composite relationships to improve code reusability.

4. Subclass is a special type, not just a role of the parent class.

5. Subclass extension, instead of overwriting or disabling the function of the parent class

 

Iv. disadvantages of combination:

1. The overall class cannot automatically obtain the same interface as the Department class

If the method subclass of the parent class is almost exposed, it may be inconvenient to use the combination, and it seems easier and convenient to use inheritance. However, from another perspective, you may not need to expose these methods in the subclass, so you can combine the applications on the client. Therefore, we recommend that you do not inherit classes that are not designed for inheritance. Classes designed for inheritance are abstract classes.

2. When creating an object of the overall class, you need to create all objects of the local class.

There may be no better method, but there is not much code in the actual application.

V. Related Principles

1. Lee's replacement principle (LSP) (from the http://www.cnblogs.com/zhenyulu/articles/36061.html below)

Liskov substitution principle (Rishi replacement principle): Subtypes must be able to replace their base types.

 

White Horse, dark horse

In turn, replacement is not valid.
Mozi Xiaoyao said: "Oh, beautiful people, love others, not beautiful people ...... "Ghost is my sister, and my brother loves my sister because the two are siblings, not because my sister is a beauty. Therefore, loving a sister is not the same as loving a beauty. It is described in object-oriented language. Beauty is a base class, and sister is a child class of beauty. As a "Love ()" method, brother accepts sister as a parameter. Therefore, this "love ()" method generally cannot accept the beauty instance.

I will not turn the example of the rectangle square below. You can go to the blog address above to learn about it.

2. Synthesis/aggregation Reuse Principle (CARP) (conversion from http://www.cnblogs.com/zhenyulu/articles/36068.html below)
Composite/aggregate Reuse Principle or carp is often referred to as Composite Reuse Principle or CRP ), it is to use some existing objects in a new object to make it a part of the new object. New objects reuse existing functions by delegating these objects.

In short, we should try to use synthesis/aggregation instead of inheritance.

O design to interfaces.
O favor composition over inheritance.
O find what varies and encapsulate it.
(From: Design Patterns explained)

Distinguish between "has-a" and "is-"

"Is-a" is strictly defined in the taxonomy meaning that one class is another class "one ". "Has-a" is different. It indicates that a role has a certain responsibility.

One common cause of incorrect inheritance rather than merging/aggregation is that "has-a" is treated as "is-".

For example:

In fact, employees, managers, and students describe a role. For example, if a person is a "manager", it must be "employee", and another person may be "Student employee". In the above design, A person cannot have multiple roles at the same time. If he is an "employee", he cannot be a "student". This is obviously unreasonable.

The error is caused by confusion between the "role" level structure and the "person" level structure, and mistaken "has-a" as "is-". Solution:

Summary:

Based on the content we mentioned above, we can find that inheritance has far more disadvantages than advantages. Although inheritance has been heavily emphasized in the process of learning Oop, it does not mean that it should be used everywhere as much as possible. On the contrary, exercise caution when using it. It can be considered only when it is clear that inheritance is the most effective in all methods. The biggest advantage of inheritance is that expansion is simple, but most of its shortcomings are fatal. However, because the advantages of simple extension are too obvious, many people do not think deeply, which causes too many problems, I hope this article will lead you to some thoughts.

 

Refer:

Http://blog.csdn.net/Cpp_Java_Man/archive/2006/05/02/705279.aspx

Http://blog.csdn.net/zjliu1984/archive/2009/06/26/4299657.aspx

Http://www.cnblogs.com/zhenyulu/category/6930.html

Http://www.cnblogs.com/bluedy1229/archive/2008/11/19/1286692.html

Author: Lance
Source: http://www.cnblogs.com/nuaalfm/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.