Sei sulla pagina 1di 16

Copyright 2006 Aloha Technology Pvt. Ltd.

CODING STANDARDS AND GUIDELINES A DEVELO PERS RULE BOOK (Aloha Technology Pvt. Ltd.)

Page 1 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

TABLE OF CONTENTS 1. INTRODUCTION. 2. NAMING CONVENTION.. 2.1 REGULAR VARIABLES 2.2 GLOBAL VARIABLES 2.3 CLASS NAMES 2.4 CLASS MEMBER VARIABLES 2.5 STRUCTURE MEMBER VARIABLES 2.6 FUNCTION NAMES 2.7 CONSTANTS 2.8 KEEP NAMES CONSISTENT 2.9 USE PRONOUNCESABLE, NON-CRYPTIC NAMES 2.10 AVOID EXTREMELY LONG NAMES 3. COMMENTS. 3.1 GENERAL GUIDELINES 3.2 USING DOXY-COMMENT FORMAT AN INDUSTRY STANDARD 3.3 TODO COMMENTS 3.4 DONT OVERDO WITH COMMENTS 4. WRITING READABLE CODE 4.1 FUNCTION LENGTH 4.2 AVOID HAVING TOO MANY PARAMETERS IN FUNCTIONS 4.3 AVOID DEEPLY NESTED CODE 4.4 USE TABS(4 SPACES) FOR INDENTATION 4.5 CURLY BRACES 4.6 DECLARE AND INITIALIZE VARIABLES WHERE THEY ARE FIRST USED 5. WRITING MAINTAINABLE CODE 5.1 DONT DUPLICATE CODE 5.2 AVOID USING #define 5.3 USE OF GETTER AND SETTER FUNCTIONS 6. WRITING CORRECT CODE 6.1 DONT SHADOW VARIABLE NAMES 6.2 USE CORRECT FORM OF DELETE 6.3 PROTECT CLASSES FROM SHALLOW COPY THE LAW OF BIG THREE 6.4 CORRECT IMPLEMENTATION OF operator = 6.5 CORRECT IMPLEMENTATION OF COPY CONSTRUCTOR 7. WRITING RELIABLE CODE 7.1 PROTECT CLASSES FROM SHALLOW COPY THE LAW OF BIG THREE 7.2 USE new AND delete INSTEAD OF malloc AND free 7.3 ERROR HANDLING WITH EXCEPTION 7.4 AVOIDING MEMORY LEAKS 7.5 POINTER VALIDATONS

Page 2 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

7.6 AVOID COMPARING STRINGS 7.7 USE OF BOOLS 8. CODE PERFORMANCE ISSUES 8.1 AVOID PASSING ARGUMENTS BY VALUE 8.2 DONT TWIST YOUR CODE 9. WRITING UNICODE AWARE CODE INTERNATIONALIZATION............................. 9.1 USE OF STRINGS 9.2 UNICODE AWARE

Page 3 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

1. INTRODUCTION Be a developer not a programmer! Programmer is anybody who knows the syntax of a language and can throw together some code that works. However, developer is someone who not only writes code that works correctly, but also writes high quality code. This document establishes rules and guidelines that must be strictly followed so as to produce a quality software product.

Page 4 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

2. NAMING CONVENTIONS Hungarian notation should be practiced while coding. This helps everyone to understand the code with a world wide accepted benchmark. 2.1 Regular variables: use mixed case variables beginning with lowercase. Example: hWnd, iFileIndex. 2.2 Global variables: global variables must start with g followed by an underscore character _. Example: g_hMutex, g_Parser. 2.3 Class names: class name must prefix with C. Example: CStudent, CTask. Example: CNewTaskDlg, CStaticLink. 2.4 Class member variables: class member variables must start with m_ Example: class CFoo { private: int m_iIndex; Color m_color; CString m_strName; }; 2.5 Structure member variables: do not use m_ for structure data members. Example: struct Foo { int iIndex; Color color; CString strName; }; 2.6 Function names: Function names must be in mixed case, starting with uppercase. They should normally be a verb, or a verb followed by noun. Avoid starting function names with nouns, as it may be confusing to the reader. Example: CheckForErrors() instead of ErrorCheck() DumpData() instead of DataDump() GetLength() instead of Length(). 2.7 Constants: For global constants, or constants declared inside classes, use all uppercase with

Page 5 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

underscores to separate words. Dont use #define for constants Example: For global variables, use uppercase names const int FOO_CONSTANT = 12; For local variables, use the normal variable naming convention const int iDimensions = 3; 2.8 Keep names consistent: Avoid using different names (or different abbreviations) for the same concept. Example: Instead of: Using all names transform, xform, and xfrm in different parts of the program to refer to the same entity Choose: One name and use it consistently 2.9 Use Pronounceable non-cryptic words: One rule of thumb is that a name that cannot be pronounced is a bad name. A long name is usually better than a short, cryptic name. Example: Instead of: double dAspRto; int iTrkChng; long lErCt; Use: double dAspectRatio; int iTrackChanges; long lErrorCount; 2.10 Avoid extremely long names: A rule of thumb is that names must contain about 2-4 words. Names with more than 4 words probably indicate design problems and must be avoided. Example: Instead of: GetLastSystemErrorDescription() Use: GetLastErrorDescription()

Page 6 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

3. COMMENTS 3.1 General Guidelines: In general, Comments must be brief Example: Instead of: /// The following code will calculate all the missing values of /// entity by applying GPL algorithm on the existing values Write: /// calculate missing values using GPL algorithm Dont restate code with comments Example: Instead of: // traverse the task list for (int i=0; i<TaskList.GetCount(); ++i). { // get the task reference CTask* pTask = TaskList.GetAt(i); // if the task priority is high if (pTask->m_ePriority == TASK_PRIORITY_HIGH) { // delete the task DeleteTask(pTask); } } Use: // delete all the tasks with higher priority for (int i=0; i<TaskList.GetCount(); ++i) { CTask* pTask = TaskList.GetAt(i); if (pTask->m_ePriority == TASK_PRIORITY_HIGH) DeleteTask(pTask); } Explain WHY instead of HOW (except when commenting in the large) 3.2 Use Doxy-Comment Format: Doxygen is a documentation system widely accepted as an industry standard featuring the most of C++ specification. We encourage to comment the code using XML based comments style (Standard ECMA-334, C# Language Specification) demonstrated bellow. Application Header File tags: Following declaration should be made only under a single application specific file, in MFC CWinApp derived class header file is

Page 7 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

ideal. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// /// @mainpage Insert subject of the Product /// <remarks>Insert remarks here</remarks> /// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// File Header Declaration: File Header Declaration describes the purpose and usage of the file with its Author and created date. Example: //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// /// @file FileName.h /// @author Insert author name here /// @date December 9, 2005 /// <summary>Insert File summary here</summary> /// <remarks>Insert remarks here</remarks> /// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////. Developers Page 7 of 12 Function Header Declaration: Function Header Declaration describes the purpose and usage of the function with its signature. Example: /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// /// <summary>Insert function summary here</summary> /// <param name="parameter ">insert parameter description here</param> /// <returns>insert return values</returns> /// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int CFoo:: Foo(long x, double y) { //.....function body....... } Understanding Doxygen Commands: @file: Indicates that a comment block contains documentation for a source or header file. Every file that contains one or more doxy comment should carry this command. @author: Starts a paragraph where one or more author names may be entered. @date: Inserts date <summary/>: A brief summary section. <remarks>: A descriptive summary, remarks section. <param name=parameter name/>: Parameter insertion command.

Page 8 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

<returns/>: return value explanation. 3.3 TODO comments: Use ///TODO: comments to remind yourself and others about work that needs to be done in the code. Example: ///TODO: replace these calculations with calls to Screen library drawGrid[n].width = ...... 3.4 Dont over do with comments: Too many comments are as bad as too little comments! In most cases, a comments-to-code ratio of 10%-30% should be sufficient. However, Doxygen comments should be brief, clear and are an exception to the above rule.

4. WRITING READABLE CODE 4.1 Function Length: Try to write small functions, no longer than 2 pages of code. This makes it easier to read and understand them, and it also promotes code reusability and maintainability. 4.2 Avoid having too many parameters in function: Functions that take too many parameters often indicate poor code design and poor usage of data structures, here designing classes could be a good option. 4.3 Avoid deeply nested code: Avoid having too many levels of nesting in your code. As a rule of thumb, try to have no more than 5 nesting levels. 4.4 Use tabs(4 spaces) for indentation: Using tabs(4 spaces) for indentation makes the code more readable. 4.5 Curly braces: Put braces at the beginning of the line Example: Instead of: void Foo(long x, double y) { //.....function body....... } Use:

Page 9 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

void Foo(long x, double y) { //.....function body....... } 4.6 Declare and initialize variables where they are first used: Variables should be declared and initialized where used. That is, the C practice of declaring all variables to the top of a function body is discouraged. Also try to always initialize variables in their declaration. Example: Instead of: long n; // .other irrelevant code here. n = Foo(); Use: // .other irrelevant code here.. long n = Foo();

Page 10 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

5. WRITING MAINTAINABLE CODE 5.1 Dont duplicate code: Duplicating code is one of the greatest evils in programming; it is the worst form of code reuse. A common reason that programmers produce duplicate code is time pressure: now we dont have enough time, so lets copy-and-paste for the moment, and later on well come back to fix it. Dont fall into this trap! Its always better to do it right the first time! 5.2 Avoid using #define: In C++, you should try to replace #define with something that the C++ compiler actually understands so that it can do better error checking: use const for constants, enum for related constants, and inline functions instead of macros. 5.3 Use of getter and setter functions: Avoid as much as possible public data members. All data members should be private or protected. To access these member variables use the getter and setter functions. But also remember, dont overdo with getters and setters.

Page 11 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

6. WRITING CORRECT CODE 6.1 Dont shadow variable names: Do not use the same name for two different variables in enclosing scopes. The second variable will shadow the first one, and this can lead into a hard to detect bug. Example: int length; if (a > 0) { //legal, but BAD! It hides the previously declared variable length int length; } 6.2 Use correct form of delete: As a rule of thumb, if new allocation is made using brackets [ ], the deletion must be made with [ ]. Example: CTask* pTask = new CTask; delete []pTask; // WRONG ! delete pTask; // OK ! CTask** ppTaskArray = new CTask[100]; delete pTask; // WRONG ! delete []pTask; // OK !

Page 12 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

7. WRITING RELAILABLE CODE 7.1 Protect classes from shallow copy the Law of Big Three: // Every class should have at least the following: class X { public: X (); // default constructor virtual ~X (); // destructor protected: private: X (const X& x); // copy constructor make it public only if needed X& operator = (const X& x); // operator equal }; 7.2 Use new and delete instead of malloc and free 7.3 Error handling with Exception: Make use of try{} catch(){} blocks so as to keep your code for handling any undiscovered errors and exceptions. 7.4 Avoiding Memory Leaks: Handles usage, GDI Leaks, Private bytes usage and Virtual memory are some of the major areas to look into while coding. Example: Instead Of: // Code with GDI leak { HBRUSH hBrush = ::CreateSolidBrush(RGB(255, 0, 0)); ::SelectObject(hDC, hBrush); ::DeleteObject(hBrush); } Use: // Code without GDI leak { HBRUSH hBrush = ::CreateSolidBrush(RGB(255, 0, 0)); HBRUSH hOldBrush = ::SelectObject(hDC, hBrush); ... ::SelectObject(hDC, hOldBrush); ::DeleteObject(hBrush); } Example: Instead Of: // Code with Handle leak { WIN32_FIND_DATA FindFileData={0}; HANDLE hFileFind = ::FindFirstFile("C:\\*.*", &FindFileData);

Page 13 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

} Use: // Code without Handle leak { WIN32_FIND_DATA FindFileData={0}; HANDLE hFileFind = ::FindFirstFile("C:\\*.*", &FindFileData); if (hFileFind) ::FindClose(hFileFind); } 7.5 Pointer validation: Pointer features the rich functionality of a language making it possible to catch hold of any instruction at any point of time. However pointers should be sparingly used with better understanding of the code and what if conditions. Example: Instead of: // what if pTask is NULL? // may raise an access violation if (pTask->m_eStatus == CTask::eStatus::TASK_STATUS_PENDING) { //.. } do: // pointer validity check avoids access violation if ((pTask != NULL) && (pTask->m_eStatus == CTask::eStatus::TASK_STATUS_PENDING) ) { //... } 7.7 Use of BOOL: BOOLS should be sparingly used in a program. The most used data type BOOL might launch your program into hassles and undiscovered behavior. BOOLs should be cautiously used as it may lose the understanding of the code, making it more difficult for others to understand and program.

Page 14 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

8. CODE PERFORMANCE ISSUES 8.1 Avoid passing arguments by value: Example: Instead of: void Foo(long x, CSomeClass obj) // NOT efficient { obj.CleanAll(); obj.SetValue(x); } do: void Foo(long x, const CSomeClass& obj) // better { obj.CleanAll(); obj.SetValue(x); } 8.2 Dont twist your code try better algorithms by re-writing the code.

Page 15 Amey

Copyright 2006 Aloha Technology Pvt. Ltd.

9. WRITING UNICODE AWARE CODE - INTERNATIONALIZATION Internationalization and localization is a challenging task for developers, particularly if the software is not designed from the beginning with these concerns in mind. Always write the code that is UNICODE aware. Your code should work for both ANSI and UNICODE encodings. A common practice is to separate textual data and other environment-dependent resources from the program code. Following considerations should be taken. 9.1 Use of Strings: Use String table for storing static text. Instead of hard coding the message strings into the application code, put it into the string table mapped to an equivalent identifier. Example: Instead Of: CString strErrDescription(Unable to connect to the Server.); Use: CString strErrDescription; strErrDescription.LoadString(IDS_ERR_CONNECT); 9.2 Unicode aware: Your code should be UNICODE aware. Always make use of Unicode equivalent APIs and coding formats. Write your application so that it can be compiled for Unicode or for ANSI. Use the _T macro to conditionally code literal strings to be portable to Unicode. strUserName = _T(); // UNICODE aware Make use of UNICODE aware functions such as lstrlen or lstrcpy. Understand the functions that react to the locale of the application.. To complete Unicode programming of your application, you must also: When you pass strings, pay attention to whether function arguments require a length in characters or a length in bytes. The difference is important if you're using Unicode strings. Use portable versions of the C run-time string-handling functions. Use the following data types for characters and character pointers: TCHAR Where you would use char. LPTSTR Where you would use char*. LPCTSTR Where you would use const char*. CString provides the operator LPCTSTR to convert between CString and LPCTSTR.

Page 16 Amey

Potrebbero piacerti anche