Drink Remodeling Series [7]--use delegation instead of inheritance

Source: Internet
Author: User

Overview

Subclasses can inherit the fields, properties, and methods of the parent class, and use inheritance to reuse the code to a greater extent.
When using inheritance, it is important to determine that the "parent class" and "subclass" defined in the code do have an objective "father-child relationship", rather than "using inheritance for code reuse", which is trifles and an embodiment of abuse of inheritance.
Misuse of inheritance destroys the objective relationship between classes, and also blurs the semantics embodied in the code.

Use delegation instead of inheritance inheritance error

When multiple classes have similar properties, methods, so that one of the classes becomes the base class, the other classes inherit the base class to implement code reuse.
When a class in a scenario is promoted to a base class, it is prudent to consider whether the class actually has a parent-child relationship with other classes, and does not constitute an inheritance relationship if there is no parent-child relationship.

How do I determine the inheritance relationship between classes?
Should be understood from the actual business and semantics (this is a trivial nonsense).

To cite a less appropriate example, although the big head son and uncle Wang next door is really too similar, but in law, the head of the son to inherit a small father is legal, and not to inherit the next door Uncle Wang.
(PS: I do not know if the big head son is a small child father's own)

Misuse of inheritance

is the vector and Stack class in Java, in order for the IsEmpty () method to be reused, the stack inherits the vector.
But vector and stack are different data structures, there is no obvious "parent-child relationship", this is a typical abuse of inheritance practices.

delegation instead of inheritance

Now the question is, how do you build the relationships of these 2 classes when the two classes do not have an inheritance relationship and one class relies on a method of another class?
This is the refactoring strategy to be explained in this article-- using delegation instead of class inheritance

Inheritance is a strongly associated relationship, and delegation is a weakly associative relationship.

Example before refactoring

This code defines the sanitation class and the child class and class that describe the "children's hand washing" thing.
In this case, the sanitation class says sanitary facilities, such as faucets and hand sanitizer, are available for people to wash their hands and, of course, for children to wash their hands, and child says he uses these sanitary facilities to wash his hands.
The sanitation class provides the Washhands () method and lets child inherit sanitation.

public class sanitation{Public    string Washhands ()    {        return "cleaned!";    }} public class child:sanitation{}

From the semantic analysis:

1. Sanitary facilities are available for children to wash their hands, which is a passive behavior. It is an active activity for children to wash their hands with sanitary facilities.
2. Children are not from the health facilities, but born from the parents of the fertilized egg, the two itself is an indirect relationship.

There is only an "exploit" relationship between the two, and there is no "inheritance" relationship. In order to embody the "exploit" semantics, we should use delegation.

After refactoring

Make the following adjustments to this code: 1. Remove the inheritance relationship between child and sanitation.
2. Define the sanitation property in the child class.
3. Define the Washhands () method in the child class, and call the Washhand () method of the Sanitation property.

public class sanitation{Public    string Washhands ()    {        return "cleaned!";    }} public class child{    private sanitation sanitation {get; set;}    Public Child ()    {        sanitation = new sanitation ();    }    public string Washhands ()    {        return sanitation.washhands ();}    }

You might have questions about the refactoring code, the amount of code is more than before, and the child needs to rely on the sanitation class, what is the benefit?
From the point of view of the code, it really does not do you any good, as you would think.

But I think the code should be able to embody objective facts and semantics-"children use sanitary facilities to wash their hands," rather than "children have to wash their hands because they inherited health facilities."

I personally have been advocating a point of view-the code level of WYSIWYG, when we see a piece of code, we know what this code can do, do not need too much rhetoric and comments, not much more, appropriate. To sum up in one word is "Yang".

Like this article: 10 years of code, I am afraid to write some of the Code "dry" (yes, I do not think it is what "dry").
"Judging whether the string is e-mail", is a very simple thing, why not directly to describe it?

public static bool e-mail (this String str) {    bool result = false;    if (!string. IsNullOrEmpty (str) && System.Text.RegularExpressions.Regex.IsMatch (str, @ "^ ([0-9a-za-z]+[-._+&]) *[ 0-9a-za-z][email protected] ([ -0-9a-za-z]+[.]) +[a-za-z]{2,6}$ "))    {        result = true;    }    else    {        result = false;    }    return result;}

"Judging whether a string is an email" is a word that can be used to clarify its semantics and logic--"The string is not empty and matches the email regular expression."

public static bool Isemail (this string str) {    String Emailpattern = @ "^ ([0-9a-za-z]+[-._+&]) *[0-9a-za-z][email Protected] ([ -0-9a-za-z]+[.]) +[a-za-z]{2,6}$ ";    Return!string. IsNullOrEmpty (str) && regex.ismatch (str, emailpattern);}

This code does not use the syntax sugar, is not what the x behavior, I am not to reflect the 2 lines of code must be better than 10 lines of code.

Drink Remodeling Series [7]--use delegation instead of inheritance

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.