Guidelines For Software Coding
Guidelines For Software Coding
Approved by
Name: Shri. Mohanachandran .R Designation : Management Representative
Issuing Authority
HEAD, Quality Assurance Department C-DAC (T) Vellayambalam, Thiruvananthapuram
For any clarifications/ corrections/ amendments in this document please contact Issuing Authority
Copyright
No part of this document may be reproduced in any form without the prior permission in writing of issuing authority
i. AMENDMENT HISTORY
1. Issue History
Issue No 1 Effective From 08-08-2007 Reason for Re-issue NA Total Doc. Pages 4 Change Report Number / Date -
Date:
06-08-2007
Name: Mohanachandran.R 2. Revision Details of Current Issue (Issue No 3) Doc Rev No. Effective From Revised/ Page Total Brief Description of change Added Rev. Doc. (If change is major, give document change report number/date only) Page No No. Pages Approved by (Signature)
Table of Contents
Sl. No
1 2 3 3.1. 3.2. 3.3. 3.4. 3.5. 3.6. 4
Contents
Introduction Scope General Guidelines Sample Coding Practice Naming Conventions Add header for each file Commenting Number of Functions, Methods /File Error Handling List of Annexure
Page No 1 1 2 2 2 3 4 4 4 4
1.
Introduction
These guidelines are being issued To promote a uniform coding style among software developers in the organization so that code generated by one developer can be easily understood by another( or by the developer long time after the development) , for review or maintenance purpose.
2.
Scope
This document describes general software coding standards for code written in any text based programming language (including high-level languages like C, C++, Visual Basic, Java and assembly languages). This will be used as the base document for several language specific coding standard documents.
3.
Essential Requirements
As part of the software development process, the following aspects are to be made mandatory prior to the beginning of the coding activity:
Standardized Folder structure should be strictly followed by the Team members as directed by the Project Leader. The modules and the coding are stored properly in the specific folder as per the guidance given by the Project Leader. Approval of the Detailed Design Document by the Project Leader must be ensured prior to implementation and clarity of the design shall be ensured through the Module Designer. Component Architecture which is based on independent, replaceable, modular components is the recommended software architecture. Classes and attributes are to be identified by the programmer with the help of Detailed Design Document. For Procedural languages, this rule is not directly applicable but still the classes and objects can be coded using structures and functions or similar constructs. The programmer should be aware of the compiler settings used by IDE and make file rules etc., For any clarification on these matters, the programmer shall discuss with the module designer or the architect.
Doc Name:
4.
General Guidelines
This section contains the general coding and construction rules that are applicable when programming in any language or technology.
4.1.
Simple Coding Practices Keep the source code as simple as possible. Avoid using complex constructs inside a program. If the operation is too long, it can be simplified by reducing the number of decision points. (A decision point is a statement where the code can take different paths, for example, if-, else-, and-, while-, and case-statements.) The nesting of loops is to be minimized and should not exceed more than 5 levels Lines of Code in each Procedure or Function should not exceed 50.
4.1.1. Code clarity Always include the braces: Even if the body of some construct is only one line long, use the braces which indicate the begin and end of statements. Braces should always go on their own line. The closing brace should also always be at the same column as the corresponding opening brace. 4.1.2. Indentation Proper indentation and line spaces to be used, which provide visual clues to the flow of implementation. 4.1.3. Use spaces between tokens Whenever you write an assignment, expression, etc. always leave one space between the tokens. Put spaces between variable names and operators. Don't put spaces just after an opening bracket or before a closing bracket. Don't put spaces just before a comma or a semicolon. 4.1.4. Operator precedence & Short Hand operators Operator precedence differs for different languages. Use brackets liberally to enforce precedence, and make it visible to the reader. 4.1.5. Inline conditionals Inline conditionals should only be used to do very simple things. Preferably, they will only be used to do assignments, and not for function calls or anything complex at all. 4.2. Naming Conventions Naming conventions of files, procedures and variables etc. should be sensible and meaningful.
Doc Name:
All names should be clear and descriptive. Do not try o abreviate unnecesasrily, except very obbious names like temp1 or n for a loop count etc. Use of capitalisation may vary in different programming languages but it is sensible to avoid names that differ only in case or look very similar. Also avoid names that conflict with standard library names.
4.2.1. Naming Package : Package naming should be of Sentence Case which should be descriptive but concise. Packages are created in accordance with language specific package conventions. 4.3. Names that conflict with standard library names should be avoided. Use upper case letters as word separators, lower case for the rest of a word First character in a name is upper case No underbars ('_') 4.2.2. Class Name:
Procedure and Function name Methods and functions are actions or rather verbs acting on noun. Suffixes and Prefixes shall be used to avoid confusion. For example: Is - to ask a question about something. Whenever someone sees Is they will know it's a question. Eg is_numeral, is capital get Value, set Value (starting word must be a verb) Max - to mean the maximum value something can have. Cnt - the current count of a running count variable.
4.3.1. Variable Naming(variable are always nouns) Use all lower case letters Use '_' as the word separator. Pointers should be prep(???????????is it preferably?) ended by a 'p'
4.3.3. Add Header for each File Each file of the source code must have a header portion containing the following information
Doc Name:
File Name : Version Number: Project Code: Project Name / Mnemonic: Product Name: Module Name: Description of the contents of the file: Author: Revision History & Date of modifications: Modified by whom and Reasons for modifications: The changes that are made in the source file can be traced using the Version control software that manages the versioning of the software. 4.4. Commenting 4.5. Add comment header for all function and procedure. Comments should be added to the code to explain implementation code. Avoid adding obvious or lengthy information. Comments should be clear, correct and up to date. details of the source
Number of functions / methods per file Number of functions / methods per file shall not exceed 20 Error Handling Error handling is to be properly managed in the coding by the programmer as per the design document specifications. During initial development, many trace statements may be included in the component or function. But as the component or function matures, the number of trace statements should gradually decrease so that the application log should not be filled with unwanted messages.
4.6.
5. List of Annexure
Sl No. 1. Name Coding Standards for Java Coding Standards for C / C++ Coding Standards for Delphi Number & Revision Status No of Pages 4
2. 3.
4 5
Doc Name:
Code Clarity
Example : Incorrect: if (condition) doStuff(); if (condition) doStuff(); while (condition) doStuff(); for (i = 0; i < size; i++) doStuff(i) Correct: if (condition) { doStuff(); } while (condition) do { doStuff(); } for (i = 0; i < size; i++) { doStuff(); }
1.2.
1.3.
1/4
File Naming
1.4.1.
Place each class in a separate file. This applies even to non-public classes (which are allowed by the Java compiler to be placed in the same file as the main class using them) except in the case of one-shot usages where the non-public class cannot conceivably be used outside of its context. Begin each file with the header as specified in the guidelines: - The file name and/or related identifying information including, if applicable, copyright information. - A history table listing dates and authors. The summaries of changes can be viewed through the log history of the Version Control software - If the file contains more than one class, list the classes, along with a very brief description of each. - Each file header should be immediately followed with: the package name the import list.
1.4.2.
2/4
The following table contains letters that go before the above prefixes.
Preprefix u k s rg
Type unsigned constant formal parameter static array (stands for range)
Example unsigned short usiStudents; void fct(const long kliGalaxies) static char scChoice; float rgfTemp[MAX_TEMP]; char m_cLetterGrade; Integer oiCount; Float ofSize Double odLimit; Boolean obSelected;
JPanel jpMainPanel JButton jbSubmit JCombobox jcbModelTypes jf Object of JFrame JFrame jfMainFrame jtxt Object of JTextField JTextField jtxtCandidateName jlbl Object of JLabel JLabel jlblName jckb Object of JCheckbox JCheckbox jckbStatus Note : prefix letter j for swing components and ignore it for awt components Eg : btnCancel
m_ member variable of a class oI Object of wrapper class Integer oF Object of wrapper class Float oD Object of wrapper class Double oB Object of wrapper class Boolean Awt / Swing Based Naming Conventions jp Object of JPanel jbtn Object of JButton jcb Object of JCombobox
1.4.3.
Variable Names
Variable names should be in SentenceCase. Names should be descriptive, but concise. We don't want huge sentences as our variable names, but typing an extra couple of characters is always better than wondering what exactly a certain variable is for.
1.4.4.
3/4
Error Handling :
In Java, while coding error handling methods, the catching of exceptions should be logged/ printed on console properly which may be quite useful for debugging purposes. Eg : try { } catch(Exception e) { System.out.println( Error in this section while accessing +e); }
1.6.
4/4
Eg: int OpenComport(int Comportnumber ) { Start the body of function; -------------------------; Return statement of function; } Indentation for Loop statements Eg: for (i = 0 ; i <= 100 ; i++) { Start the body of loop; ----------------------; End statement of loop; } Indentation for conditional statements Eg: if (ReadFlag) { Start of the block; ------------------; End of block; } else 1/4
Start of the block; ------------------; End of block; } switch(LEDNumber) { case 0: Start of body; -------------; End of body; break; case 1: Start of body; -------------; End of body; break: ----------; ----------; case n: Start of body; -------------; End of body } Note: in the case of switch statement if the number of lines in the body is a few you can avoid the indentation tab
2.2.
Naming Conventions
The naming of the variables, classes, objects, functions, or files must be meaningful/descriptive and concise words that is related to the entity of the object and relevant to the situation.
General :- Never use _ in variable or function names it shall be a continuous string with each constituent word starting with an uppercase letter . Names that conflict with standard library names should be avoided. Variables : Variables shall be named as Nouns The first character should be lower case. All word beginnings after the first letter should be upper case as with class names. 2/4
The following prefixes for variables are preferred according to Hungarian notation Byte - b Integer n Float - f Character c String s Pointer- p Global g Reference - r Eg: int nComputerNumber;
Functions Functions shall be named as verbs acting on a noun and the relevant Suffixes and Prefixes shall be used to avoid confusion Eg: int FindComputerNumber(); int IsMax(); Loop indexes Loop indexes shall be named as i,j,k,l File naming -- The file names must be meaningful words related to the entity of the object and relevant to the situation, always consult with the designer Enum names - All uppercase with _ word separators Macro and Constant Values - Macros and Constant shall be defined with uppercase letters, only use _ between constituent words. Eg: #define MAXIMUM_LIMIT 1000;
const int MAXLIMIT=100;lqs
2.3.
The file names must be meaningful words related to the entity of the object and relevant to the situation, always consult with the designer.
Place the each source and files in the relevant directory. Begin each file with the header as specified in the guidelines. The file name and/or related identifying information including, if applicable, copyright information. A history table listing dates, authors, and summaries of changes. If the file contains more than one class, list the classes, along with a very brief description of each. Immediately follow each file header with: The inclusion of header files list The global variables if any
3/4
2.4.
Error Handling : Error handling is properly managed in the coding by the programmer as per the design document specifications. During initial development, many trace statements may be included in the component or function. But as the component or function matures, the number of trace statements should gradually decrease so that the application log should not be filled with unwanted messages. In C programmer only should implement the error handling mechanisms. In C++, while doing error handling techniques, the catching of exceptions should be logged/ printed on console properly which may be quite useful for debugging purposes. Eg : try { } catch(Exception e) { } printf( Error in this section while accessing +e);
4/4
Editor Settings Each tab will be equivalent to 8 spaces. Enable Smart tab property at Tools-> editor options.
3.2.
White Space Usage Blank Lines: A blank line should also be used in the following places:
After the copyright block comment, package declaration, and import section. Between class declarations. Between method declarations.
3.3.
Packages Runtime packages will contain only units / components required by other components in that package. Packages will be named according to the following templates: "iiilibvv.pkg" - design package "iiistdvv.pkg" - runtime package where the characters "iii" signify a 3-character identifying prefix. This prefix may be used to identify the company, person or any other identifying entity. The characters "vv" signify a version for the package corresponding to the Delphi version for which the package is intended. Note that the package name contains either "lib" or "std" to signify it as a runtime or design time package.
3.4.
Files Project Files: Project files will be given descriptive names. For example, The Delphi Developer's Guide Bug Manager is given the project name: DDGBugs.dpr. A system information program will be given a name like SysInfo.dpr. Unit Name: Unit files will be given descriptive names. For example, the unit containing an application's main form might be called MainFrm.pas.
1/5
Naming Conventions Except for reserved words and directives, which are in all lowercase, all Pascal identifiers should use InfixCaps, which means the first letter should be a capital, and any embedded words in an identifier should be in caps. Unit Naming: Use InfixCaps. Class/Interface Naming: UseInfixCaps, Begin each type declaration with capital TMyType Field Naming: Use InfixCaps. Begin each type declaration with a capital F. When thinking about naming conventions, consider that one-character field names should be avoided except for temporary and looping variables. Method Naming: Method names should use the InfixCaps style. Start with a capital letter, and capitalize the first letter of any subsequent word in the name, as well as any letters that are part of an acronym. All other characters in the name are lower case. Do not use underscores to separate words. Local Variable Naming: Local variables follow the same naming rules as field names, except you omit the initial F, since this is not a Field of an object. Reserved Words: Reserved words and directives should be all lowercase. Type Declarations: All type declarations should begin with the letter T Array naming: Names for array types must be meaningful to the purpose for the array. The type name must be prefixed with a T character. If a pointer to the array type is declared, it must be prefixed with the character P.When practical, variable instances of the array type will be given the same name as the type name without the T prefix. Record Types: A record type shall be given a name meaningful to its purpose. The type declaration must be prefixed with the character T. If a pointer to the record type is declared, it must be prefixed with the character P and declared immediately prior to the type declaration. Loop control variables are generally given a single character name such as I, J, or K. It is acceptable to use a more meaningful name as well such as UserIndex. Boolean variable names must be descriptive enough so that their meanings of True and False values will be clear.
2/5
Type
Example bStillGoing :Boolean chLetterGrade: char sFirstName: string iindex:integer fPercent:float dCurrentDate:Date dtprevDate:DateTime; char szName[NAME_LEN];
Old-Style Null Terminated String Array (to be concatenated with another prefix, such as s
Cu Dc H Inst Ov P Pg
Currency DeviceContext Handle Instance of an object OleVariant Pointer Not a data type, but a scope specifier: Project Global (declared in interface section of unit)
T V Ui Ug
Time Variant Byte,Word Not a data type, but a scope specifier: Unit Global (declared in the implementation section of unit)
ws
Widestring
3/5
3.6.
Code Layout Standard header for new files: Here a template of the header that must be included at the start of all files (values in between $ will be replaced by the CVS server automatically):
{**************************************************************** {* {* CalculateTime.pas {* Delphi Implementation of the Class TCalcualteTime {* Generated by: {* Created on: Date
{* Modified on: $Date$ (GMT) {* Module Designer: {* Architect: {* Author: ... {***************************************************************** {* Modification history: {***************************************************************
3.7.
Comments It is helpful to place comments near the top of unit to explain its purpose. Remember that misleading comments are worse than no comments at all.
3.8.
Block Comments A block comment is always used for the copyright/ID comment at the beginning of each source file. It is also used to "comment out" several lines of code.
4/5
3.9.
Statements if Statements Do not nest if statements more than five levels deep. case Statements The actions statements of each case should be kept simple and generally not exceed four to five lines of code. If the actions are more complex, the code should be placed in a separate procedure or function
3.10.
Structured Exception Handling Exception handling should be used abundantly for both error correction and resource protection. This means that in all cases where resources are allocated, a try..finally must be used to ensure proper deallocation of the resource
5/5