Refactoring Method 30: replace type code with class (replace type code with Class)

Source: Internet
Author: User


Class has a numeric type code,But it does not affect the behavior of the class. Replace the Value Type Code with a new class.

Motivation: C-basedProgramming LanguageType Code or enumeration value is very common. If there is a meaningful symbolic name, the type code is quite readable. The problem is that the symbol name is only an alias. The value behind the symbol is what the compiler sees and checks the type. Any function that accepts the type code as a parameter actually expects a value and cannot force the use of the symbol name. This greatly reducesCodeBecome the source of a bug.

If such a value is changed to a class, the compiler can perform type checks on the class. By providing a factory function for this class, you can always ensure that only valid instances are common and that they are passed to the correct host object.

However, before using replace type code with class (replace type code with class), you should consider other replacement methods of type code. Only when the type code is pure data (that is, the type code will not cause behavior changes in the switch statement) Can you replace it with a class. More importantly, any switch statement should be removed using replace conditional with polymorphism (replacing conditional expressions with polymorphism. To perform such refactoring, you must first use replace type code with subclass (replace type code with subclass) or replace type code with State/Strategy (replace type code with State policy ), process the type code.

Even if a type code does not cause behavior differences due to its numeric values, some behaviors in the host class may be more suitable for the Type Code class, therefore, you should also pay attention to whether it is necessary to use the move method to move one or two functions.


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: 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.