C ++ design and development specifications (3): Type Design Specifications

Source: Internet
Author: User

3. Type Design Specifications "Everything is simple and beautiful"There are many types in C ++, including (specific) classes, base classes, interfaces, structures, enumerations, arrays, and so on. In this specification, we do not discuss abstract classes and interfaces in detail, because these two types belong to a special logical group, which is related to scalability. We will discuss them in the extensibility design specification. Any programming language can be regarded as a type system. In this type system, each type assumes its respective responsibilities and has its own meaning: n (specific) class: encapsulate behaviors and attributes on the premise of following a specific development closed principle. Use class declaration. N base class: moderately encapsulate behaviors and attributes on the premise of following a specific development closed principle. Use class declaration. N interface: abstracts a specific behavior and provides an abstract classification criterion for objects. It should be basically stable. Use interface declaration. N structure: defines small and simple types. Use struct declaration. N enumeration: used to define a group value, which represents a logical classification. For example, every day of a week. 3.1. Select the type to be designed.In a type system, different types apply to different purposes. Therefore, different rules indicate different meanings. L RecommendationUse the base class. If: A. implements a specific interface ( Optional)B. for subclass, it does have abstract meaning C. it shares members (attributes, functions) with sub-classes or/and defines virtual functions to abstract D. it has/does not have status L RecommendationUse abstract classes. If: E. has all the features of the base class F. cannot be instantiated (at least one pure virtual function) L RecommendationIf:. it represents the abstraction of A Class of behavior. Such a class of behavior can be used as a classification rule to distinguish other objects of different classes B. its definition should be basically stable; otherwise, the abstract class should be used instead of the Interface C. it defines functions rather than implementing functions and does not have any status D. well-defined interfaces only do one thing l RecommendationUse the structure. If:. it logically represents an independent value, similar to basic types (such as int and double) B. it does not need virtual functions (including virtual destructor) C. it is always instantiated in the stack, the instance is relatively small and the lifecycle is relatively short or often embedded in other objects l RecommendationUse static classes. If the class you designed has the following features:. all the functions it defines are public static B. it does not need to be instantiated C. it is often used to define some help functions or to integrate a specific function based on simplicity considerations. 3.2. General Design Features  √ RequirementsDifferentiate interfaces, structures, and classes: StructureUse the struct keyword declaration to define data-centric entity types, such as struct pagesetting. InterfaceUse the interface (struct) keyword declaration to define the object type of the abstract behavior set, such as interface idrawing. ClassUse the class keyword declaration to define behavior-centered entity types, such as class tokenparser. × NoUse private and protected inheritance unless you have. For example, // bad practice: use private inheritance to combine Class A {} Class B: Private A {} // good practice: use private members to combine Class A {} Class B {private: A M_a ;} × NoUse virutal inheritance unless you have. For example, // poor class base1 {} class base21: virtual public base1 {} class base22: virtual public base1 {} class base3: Public base21, public base22 {} l RecommendationDo not over-use multi-inheritance, especially implement inheritance. 3.3. Class Design √ RequirementsIt is easier to write a small class instead of a giant class, and it is easier to ensure correctness, test, and use. However, the category bears too many responsibilities, which weakens encapsulation. L RecommendationReplace inheritance with combinations to avoid the burden of inheritance: inheritance is the second closely coupled relationship in C ++, second only to youyuan relationship. One of the principles of software engineering is to reduce coupling. When appropriate, use combinations instead of inheritance. Exceptions:If you need to rewrite the virtual functions of the base class, if you need to access the protection members of the base class, if you need to control polymorphism, if you need to construct an existing object before the base class, or destroy this object after the base class. × NoDisclosing internal data Data Hiding is a powerful abstraction method and a powerful modular mechanism. Avoid exposing internal data handles/pointers to the outside. For example, Class component {public: char * getbuffer () {return m_buffer;} // const char * getbuffer () const {return m_buffer;} // good private: char * m_buffer ;} 3.4. Design of abstract classesL RecommendationDo not define any data members in the abstract class. √ RequirementsThe abstract class defines protect rather than public/private constructor. For example, class addinbase {public: Virtual void authorizing () = 0; protected: addinbase () {}} L RecommendationUse interfaces to define the behavior of abstract classes. For example, class icomponent {virtual void addcontrol () = 0; virtual void pendingmodification () = 0;} Class component: Public icomponent {public: Virtual void addcontrol (){...} Virtual void pendingmodification () = 0 ;} 3.5. Interface Design √ RequirementsOne interface only does one thing. × NoDefine an interface if the function defined by this interface is unstable. × NoDefine Redundant pure virtual functions with ambiguity in the interface. For example, interface ilayout {// Number of pages returned, the page index starts from 0 virtual int getactivepage () const = 0; // returns the number of pages passed to the UI parameter, and the page index starts from 1, returned value = getactivepage () + 1 virtual int getui activepage () const = 0; // redundancy} 3.6. Structure Design × NoUse the C-style definition method. For example, // poor typedef struct tagcolorswatch {...} Colorswatch; // struct colorswatch {...}; √ RequirementsProvides a default constructor for the structure. √ RequirementsSet the copy constructor as a private/protected member. If you do not need to copy the constructor. For example, struct exportconfiguration {protected: exportconfiguration (exportconfiguration & Other ){}}; √ RequirementsProvides a copy constructor for the structure. If: the default copy constructor behavior is not required. √ RequirementsIt is the structure overload operator =. If: the default operator = action is not required. √ RequirementsOperator =, Operator! =, If: the default operator =, Operator! = Action is not required. For example, struct textproperties {const wchar_t * fontname; bool bold; bool italic; bool operator ==( textproperties & Other) {return (bold = Other. bold) & (italic = Other. italic) & (strcmp (fontname, other. fontname) = 0 ));}}; × NoThe design is comprehensive and flexible. For example, // bad pagecombinemergesetting {const wchar_t * sourcefilename; int sourcepage; bool ismerge; bool iscombine; graph: cdrect targetrectangle; // valid graph when ismerge = true :: cdrect targetpage; // valid when iscombine = true} // Well, rewrite it to two structures: struct mergesetting {const wchar_t * sourcefilename; int sourcepage; graph: cdrect targetrectangle ;} struct combinesetting {const wchar_t * sourcefilename; int sourcepage; graph: cdrect targetpage;} l RecommendationThe number of elements in the structure should be moderate. If the number of elements in the structure is too large, you can consider using some principle to form different sub-structures to reduce the number of elements in the original structure. L RecommendationCarefully design the layout and arrangement sequence of elements in the structure to make the structure easy to understand, save space occupation, and reduce misuse. L RecommendationUse the _ declspec (align (x) method to define the byte alignment of the structure: for example, // define an 8-byte alignment structure _ declspec (align (8 )) struct a {double A, int B ;} 3.7. Enumeration Design × NoUse the C-style definition method. For example, // poor typedef Enum tagcolorswatchtype {...} Colorswatchtype; // The Enum kcolorswatchtype {...}; √ RequirementsEnumeration is preferred, rather than static constants or macros. For example, // poor struct applicationinfo {static const int unknownproduct = 0; static const int businessproduct = 1; static const int newsproduct = 2 ;...}; # Define freeproduct 3 // Enum kproducttype {kproducttype_unknown, kproducttype_business, kproducttype_news, kproducttype_free} × NoApplies enumeration to an open set. For example, the version of the operating system and the name of a friend. × NoInclude the Sentinel value in the enumerated value. For example, // Enum k1_type {k1_type_unknown = 0, k1_type_circular = 1, kproducttype_rectangular = 2, kproducttype_lastvalue = 2 // no need to define this enumerated value} √ RequirementsProvides zero value for simple enumeration types. For example, Enum kcompressiontype {kcompressiontype_none kcompressiontype_gzip, kcompressiontype_deflate} Enum krequesttype {krequesttype_error, krequesttype_warning, krequesttype_information} √ RequirementsUse a plural noun or noun phrase to name and Mark enumeration. For example, Enum kfile1_modes {kfile1_modes_read = 1, kfile1_modes_write = 2, kfile1_modes_readwrite = kfile1_modes_read | kfile1_modes_write ,}

 

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.