Office Source Code Style Guidedave Parker, 6/30/95
AbstractThis document outlines a general style guide for C and C source code in Office Development. The main purpose here is to list features of C which we will use and which we will avoid, along with the basic rationale for doing so. There are also standards for basic coding issues for the sake of consistency within the code and robust constructs. This is not a complete list of C / C language features with commentary. Rather, it mentions only the issues we consider important. Knowledge of C is assumed.Contents1. GENERAL GOALS 32. CLASSES 32.1 CLASS VS. STRUCT 42.2 PUBLIC, PRIVATE, AND PROTECTED MEMBERS 42.3 DATA MEMBERS 42.4 VIRTUAL FUNCTIONS 52.5 CONSTRUCTORS 52.6 dESTRUCTORS 62.7 NEW AND DELETE 72.8 OPERATORS 72.9 INHERITANCE 82.9.1 Inheritance of Interface vs. Implementation 82.9.2 Inheritance vs 102.9.3 Multiple Inheritance 113. Other C Features 113.1 Constants and Enumerations 123.2 References 123.3 Const Parameters and Functions 133.4 Default Arguments 133.5 Function Overloading 143.6 Operator OverLoading 144. Common C / C
ISSUES 144.1 #IFDEFS 144.2 GLOBAL VARIABLES 154.3 MACROS AND INLINE FUNCTIONS 164.4 OPTIMIZATION 164.5 WARNINGS 174.6 PRIVATE DATA AND FUNCTIONS 174.7 TYPEDEFS 174.8 BASIC DATA TYPES 174.9 POINTERS 184.10 SWITCH STATEMENTS 194.11 ASSERTS 194.12 ERRORS AND EXCEPTIONS 195. FORMATTING CONVENTIONS 205.1 NAMING CONVENTIONS 205.2 FUNCTION PROTOTYPES 215.3 VARIABLE DECLARATIONS 225.4 CLASS DECLARATIONS 225.5 COMMENTS 235.5.1 File Headers and Section Separators 235.5.2 Function Headers 245.5.3 In-Code Comments 255.5.4 Attention Markers 255.6 MISC. FORMATTING CONVENTIONS 265.7 SOURCE FILE ORGANIZATION 275.7.1 Public Interface Files 275.7.2 Private Interface Files 285.7.3 Implementation Files 285.7.4 Base Filenames 296. INTERFACES TO DLLS 296.1 C FUNCTIONS AND GLOBAL VARIABLES 296.2 COMMON C / C PUBLIC HEADER FILES 296.3 LIGHTWEIGHT COM OBJECTS AND ISIMPLEUNKNOWN 307. APPENDIX A: BASIC HUNGARIAN REFERENCE 337.1 MAKING HUNGARIAN NAMES 337.2 Standard Base Tags 337.3 Standard Prefixes 347.4 Standar D Qualifier 35
1. General GoalsC is a complex language that provides many ways to do things, and going prop hole hog "on all of its features can lead to confusion, inefficiency, or maintenance problems. All Office developers need to become experts on the features we will use, and avoid the others in order to form solid conventions within the group that we are all comfortable with. Our use of C features will be fairly conservative. We Yun much rather err on the side of just dealing with C, which we Zhen e all used to, then screwing up our app with a new concept that not all of us are used to.Underlying the choice of all of the style decisions are a few basic goals, as listed below. When in doubt about a particular issue, always think about the spirit of these goals. Sometimes these goals will conflict, of course, and in these cases we try to either prioritize the tradeoffs or use experience (either our own or from other groups that have used C extensively) .1. Simplicity. WHEN in doubt, Keep IT Simple. Bugs are related mostly to complexity, not code.2. Clarity. The code should do what it looks like it Zha doing. Other people need to be able to understand your code.3. Efficiency. Speed and size are important. Using C
does not imply big and slow. There are plenty of perfectly reasonable ways to make things as fast or faster than the normal C way. Speed and size often trade off, and most people probably err on the side of choosing speed too often. Remember that 20% of the code is responsible for 80% of the time. in most cases, we Zhen e more concerned about fitting comfortably in less RAM.4. appropriateness. Use the language construct that is appropriate for the abstraction or operation you are trying to do. do not abuse the language. Don Yang use a construct just because it happens to work. Definitely don Yang use a strange construct to amaze and confuse your friends to try to show how smart you are.5. Natural transition from C to C WE All Used to Be C Programmmers. Others That Look Atur Code Are Still C Programmers (EG Word and Excel). When Possible, Avoid C
constructs where a C programmer Zha instinct causes a wrong assumption.6. Catch Errors Early. Having the compiler catch an error is ideal. Having debug code (eg Asserts) catch it is the next best thing, etc. Declare things in such as way as to give the compiler the best chance at catching errors.7. Fast builds. Total generality and modularity can cause lots of inter-dependencies between files, which can have a dramatic impact on build times. This is a constant time sink for everyone. It is often worth rearranging things a little to make incremental builds faster.8. Consistency. The whole point of having a style guide is that programmers are never totally autonomous, even when the group has strong code ownership. Other people need to read and understand Your code. Eveyone Has To Give a little to have a consistent style guide, but everyone gains it stockime 抯 code.2. Classes C
classes are a nice way to encapsulate code and data into a single unit, which provides a good paradigm for object-oriented implementations as well other features such as flexible access control, convenient and type-safe polymorphism, and the possibility of via code reuse inheritance .At the most general, classes are an extension to the built-in typing of C which allows you to define your own types along with the operations on that type. Taken to the extreme, every piece of data in a program could be an instance of a class. However, we will not go nearly this far in Office. We will use classes when there is a good reason to, such as the concept being implemented is inherently object-oriented or polymorphism is required. It has been the experience of many people that programs that use classes for everything evolve into systems that are complex and inefficient. Although this may not be the fault of any particular class, complex class hierarchies can lead to needless complexity, and ov Erly Abstract Concepts Can Easily Lead To INEfficient.
In general, we will avoid allocating classes on the stack and passing classes by value, because this is where the use of constructors and destructors gets you into the most trouble. Most classes should be allocated via new, freed by delete, and passed by pointer . in addition, we will never declare a global variable which is an instance of a class that has a constructor, because this causes a bunch of C runtime stuff to get linked in and stuff to happen at boot time to construct the thing, which is a big performance hit. Using only heap-allocated classes implies we Yun l probably use classes only for relatively complex objects that you would normally have in the heap anyway, not simple things like basic data types. Beyond this, it is a judgment call when . to use a class use one if there is a good reason, but not if a more straightforward solution is just as good.Summary: use classes to encapsulate the implementation of an object-oriented concept. use classes to implement polymorphism . Avoid allocating class instances on the stack and passing them by value. Use new and delete, and pass them by pointer. This implies not using classes for simple data types. Never declare a global instance of a class that has a constructor. Not everything is as class. Use them only when you gain something.2.1 class vs. StructIn C , a struct can also have member functions and operators and everything else that a class can have. In fact, the only difference between a class and A Struct Is That All Mess. However, We will not use this as the deciding point bagween using a class vs.
. A struct To match the normal intuition, we will use a class if and only if there are member functions included.Summary: Use a class instead of a struct if and only if there are member functions.2.2 Public, Private, and Protected membersAs stated above, structs default to public access and classes default to private access. However, we will depend on the default only in the case of structs (where we leave all the data implicitly public). For a class, we will declare all members (Both Data and Code) Explicitly As Public, Protected, or Private, And Group Theim INTO Sections in That Order. for example: Class foo {public: foo (); ~ foo (); void hey; void ACK (); protected: int m_iValue; private: int m_iStuff; void LocalHelperSub ();}; Summary: Declare all class members explicitly as public, protected, or private, in groups in that order.2.3 Data MembersData members should use the naming Convention m_name where name is a normal hungarian local variable name. this makes member function implementations easier to read (no confusion about member vs. local data), and allows the use of the same Hungarian name for, eg, parameters and members. See the example below.Data members should normally not be declared public because this usually defeats the .. purpose of the class abstraction To efficiently export a data member, declare inline get and set member functions This will get optimized into the same code as a public data member For example:. class Counter {public: int CItems () const {return M_citems;} void setcitems {m_citems = CItems;} private: int m_citems;
Summary:
Data members use the naming convention m_name. Do not declare public data members. Use inline accessor functions for performance.2.4 Virtual FunctionsVirtual functions are used to allow derived classes to override a method in a base class by providing their own implementation in a way that always causes the most-derived version to be called whenever a method is called through an object pointer, even if that pointer is declared as a pointer to the base class. This is usually done to implement polymorphism, and that Zha when we Yun l use them. for example, all COM interface methods are virtual because you are always going for polymorphism via a standard interface.Unlike simple member functions, virtual functions incur some overhead due to need to call through the vtable. If a class contains at least one Virtual Function THE DATA SIZE OF Each Instantiated Object Will Be 4 bytes Larger Than THE Combined Size of The Declared Data in ORDER To Hold The VTable Pointer. After The First Vi rtual function, each additional one only adds another entry to the class vtable, which is static and per-class (nothing per object), so the main concern here is whether a class has any virtual functions at all. In addition to the memory overhead .................... ..
Perhaps the worst part is that virtual functions can not be inlined, so there will always be a function call, even when the work is trivial. Because they have overhead, you should not use virtual functions in a class unless you need to. However, make sure you do use them when it makes sense. In particular, if you have a base class which requires a destructor, then the destructor should definitely be virtual to allow derived classes to destruct any added members properly. If the destructor were not virtual, then in a context where polymorphism is being used (so the object pointer is declared as a pointer to the base class), the base class destructor will always get called, even for an object of a derived class that added data members and declared its own destructor in an attempt to free them. The derived class Zha destructor will only get called if the base class destructor is declared virtual. This scenario applies to many other kinds of methods that you will add to your classes. in Fact, MOST OF THE Methods in a base class might be this way. this issues is discussed in more detail in the inheritance section.
Note that although virtual functions have a performance penalty over regular member functions, they are often the most efficient way to implement a concept such as polymorphism where the alternative would be large switch statements (not to mention the benefits of the object-oriented encapsulation). Summary: use virtual functions to implement polymorphism. Virtual functions have overhead, so don Yang use them unless you really should. A destructor in a base class should always be virtual if polymorphism is intended.2.5 ConstructorsAh, constructors Every new C . Zha programmer nightmare This is one reason to try to minimize the use of constructors -. C programmers aren Yang used to them and will get confused Another reason is the infamous performance overhead of calling a function (unless it Zha inline) and doing work. At Possibly Unexpected and / or Redundant Times.however, Using Constructionors Can Eliminate The Dangers of Uninitialized Data And Can Also Made The Code Simpler To Read D to it). Judicious Use of destructors (see Below) Which Match The Constructors Can Also Help Prevent Memory Leaks and Other Resource Management Problems.
Fortunately, the issue is mainly one when classes are declared on the stack or passed by value, both of which we will avoid. Most of our classes should be dynamic memory objects which will be passed around by pointer. In this case, the constructor is essentially just a helper function for the functions that create these dynamic objects. Using a constructor for this purpose is reasonable to ensure a clean and consistent initialization (if you make sure to initialize all data members), but to prevent potential performance problems due to redundant initialization the constructor should not do anything expensive. Simply assigning a constant or a parameter value to each data field is about right. Very simple constructors can be made inline. Most importantly, a constructor should never be able to fail, because lacking a fancy exception Handling Mechanism, The Caller Has No Way to Handle This In Some Cases. Any Initialization That Can Fail (EG Memory Allocations) SHOULD BE PUT IN A separate initialization member function (called, eg, FInit). When this is the case, it is often useful to encapsulate the creation of an object in a function (a global function or a member of another class) that calls new and then FInit for THE Object, And Returns The Result of Finit. for Example: Class Foo {Public: Foo (INT CLINES) {m_hwnd = NULL; M_CLINES = Clines} Virtual ~ Foo (); BOOL FINIT (); Void Dosomething (); private: HWND M_HWND; INT M_CLINES;}; Bool Fcreatefoo (INT CLINES, FOO ** PPFOO) {IF (* Ppfoo = New foo (clines) == NULL) RETURN FALSE; if (* ppfoo-> finit ()) Return True; delete * ppfoo; * ppfoo = null; returnaf
Bool foo :: finit () {m_hwnd = CreateWindow (...); return (m_hwnd! = Null);
Summary: Do not do expensive work in a constructor. If you do make a constructor, make sure to initialize all data members. Very simple constructors can be made inline A constructor should never fail Do memory allocations and other potential failures. in an FInit method. Consider making a creation function that encapsulates the new and FInit operations.2.6 DestructorsIf a class has resources that need to be freed, then the destructor is a convenient place to put this. The normal case for us will be that this is just the central place to free resources for an object that is freed via delete (see below). The trickier use of destructors is for stack-allocated classes, but we Zhen e going to avoid that by not using classes on the stack. A destructor should be careful to destroy an object properly regardless of how it was created or used. Furthermore, if you choose to implement a method that frees any resources before the actual destruction, make sure to reset those fields (eg set po inters to NULL) so that a destructor will not try to free them twice. It is not necessary for the destructor to reset any fields, though, because the object can not be used after it is destructed.Like a constructor, a destructor can never fail . Also, as stated above, a destructor in a base class should always be declared virtual to make polymorphism work.The destructor for the above example would be defined as: Foo: ~ Foo () {if (! m_hwnd = NULL) DestroyWindow ( m_hwnd);