Reconstruction Method 39: replace conditional with polymorphism (replace conditional expressions with polymorphism)

Source: Internet
Author: User

You have a conditional expression that selects different behaviors based on the object type.Place each branch of the conditional expression into the override function of a subclass, and declare the original function as an abstract function.

Motivation: the most fundamental benefit of polymorphism is that if you need to take different behaviors based on different types of objects, polymorphism makes it unnecessary to write certain conditional expressions.

Because of the polymorphism, you will find that "switch statement of type" and "If-then-else statement based on type name" are in the object-orientedProgram.

Polymorphism can bring many benefits to you. If the same set of conditional expressions appear in many places of the program, the biggest benefit is the use of polymorphism. When using conditional expressions, if you want to add a new type, you must search for and update all conditional expressions. However, if polymorphism is used, you only need to create a new subclass and provide the appropriate functions in it. Class users do not need to understand this subclass, which greatly reduces the dependency between various parts of the system and makes the system upgrade easier.

 

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.