Coding Conventions for C++ and Java applications ...
University of Houston College of Optometry
Core Programming Module
Coding Conventions and Best Practices
Date: Sept 29, 2009
Hope M. Queener
Introduction
The following set of coding conventions is used by the Core Programming Module at University of Houston College of Optometry (UHCO). The Core Programming Module serves UHCO principal investigators by developing applications that facilitate scientific research. The applications may perform data acquisition, image acquisition and analysis, signal analysis, psychophysics control or other data analysis. The programming languages primarily used by the developers in the Core Programming Module are The Math Works MATLAB, Microsoft (MS) C++ (version 6.0 with MFC and Visual Studio .net 2005), MS C#, MS Visual Basic and Sun Java.
The following set of conventions is an attempt to conform to common programming practices in the software development industry. They are based on experience of the Core programming team and on standards promoted by Microsoft, The Math Works and various developer forums. Developers at UHCO, whether or not they are directly associated with the Core Programming Module, are encouraged to adopt these practices.
In this development environment, programming of a single application is generally coded one developer at a time, but may be passed on to several developers as time passes and the application grows and changes. Occasionally, two developers will be contributing to a single application simultaneously. These conventions aim to help developers to organize their code and facilitate maintenance as code is handed off to other members of the labs, colleagues at other institutions and junior developers. These conventions also assist the coding and development process for the sole developer, by providing consistent style throughout projects.
This document begins with an overview section of best practices for all languages, followed by specific coding conventions for MATLAB, C++, C#, Visual Basic and Java. The final pages include the appendices of third-party documents on language conventions and references.
Table of Contents
1 Best Practices for All Languages 1
1.1 General Source Code Organization 1
1.1.1 Use source code file names that reflects the content of the file 1
1.1.2 Avoid spaces in file names 2
1.1.3 Avoid changing names of source code files to reflect versions 2
1.1.4 Avoid hard-coded path names in source files 2
1.1.5 Develop and test as a least privileged user 3
1.1.6 Maintain only project source files in the source code folder 3
1.1.7 Maintain backup development directories 3
1.1.8 Back up files to another device or backup media 4
1.1.9 Create an installer file for your application 4
1.2 General Naming Conventions 5
1.2.1 Use full, meaningful names for variables and functions 5
1.2.2 For variable names choose adjectives and nouns 5
1.2.3 For variable names and function arguments use “camel” notation 5
1.2.4 For function names, use a strong verb followed by an object. 6
1.2.5 For function or method names, use title (Pascal) case 7
1.2.6 Boolean variables start with “is” 7
1.2.7 Name Boolean return arguments as true if the result is successful 7
1.2.8 Name Boolean selection variables as “Selected” or “On” 7
1.2.9 Name constants using all capitals and underscores. 8
1.2.10 Use only well-accepted acronyms or abbreviations and do so sparingly. 8
1.2.11 Include units in variables representing physical quantities 8
1.2.12 Use single-character variables sparingly and with clear purpose 9
1.2.13 Avoid arbitrary abbreviations in variable names 9
1.2.14 Use “temp” in a variable only if it is truly temporary 9
1.2.15 Avoid the use of underscores in variable or function names 10
1.2.16 Avoid “Hungarian Notation” 10
1.2.17 Avoid hard-coded path names in source files 10
1.3 General Programming Conventions 11
1.3.1 Use static variables or constants rather than hard-coding values 11
1.3.2 Avoid global variables 11
1.3.3 Use loop or index variables consistently in your program 11
1.3.4 Check all possible conditions in a switch/case statement. 12
1.3.5 Use break or continue instead of goto statements. 12
1.3.6 Initialize all variables at declaration or constructions 12
1.3.7 Declare one variable per line 13
1.3.8 Maintain a constant layout style. 13
1.3.9 For long expressions, put separate conditions on separate lines. 14
1.3.10 Compare numeric values from lowest to highest to mimic math expressions 15
1.3.11 Indent argument lists for functions that wrap to the next line 15
1.3.12 When you want to copy and paste, consider redundancy 16
1.3.13 When you want to copy and paste, consider a new function 16
1.3.14 Aim for source code modules of 1000 lines or less 16
1.4 General Source Code Documentation 19
1.4.1 Include an introduction comment at the top of the source file 19
1.4.2 Include copyright information 19
1.4.3 When declaring variables, add comments on the same line 19
1.4.4 Comment on the purpose of a conditional block of code or loop 20
1.4.5 Describe each routine briefly at the top of the routine. 20
1.4.6 Document the source of algorithms that are used 20
1.4.7 Comment on the routine's limitations 21
1.4.8 Document flags to the bit level 21
1.5 General Error Checking and Debugging 23
1.5.1 Check the arguments to a function or procedure 23
1.5.2 Check preconditions and postconditions 23
1.5.3 Use messages to signal code that should never be executed 23
1.5.4 Detect and handle an error that affects the rest of a routine 23
1.5.5 If an error is detected in a routine, consider notifying the caller 23
1.5.6 Remember that error handling code is vulnerable to errors 23
1.5.7 Avoid using a returned argument for both error and result 24
1.5.8 Remove the error checking code that hinders performance 24
1.5.9 Retain error checking that can assist the user 24
1.5.10 Use meaningful, polite and grammatically correct messages 24
1.5.11 Reserve assertions for debugging purposes. 25
1.5.12 Test subsystems with parallel algorithms in debug versions 25
2 MATLAB Coding Conventions 27
2.1 Source Code Organization 27
2.1.1 Use functions rather than scripts 27
2.1.2 Use separate m-files for generic operations 27
2.1.3 Keep specific functions in the same m-file that calls them 27
2.1.4 Add only general toolboxes to the MATLAB path 27
2.2 Naming Conventions 27
2.2.1 When using GUIDE, rename the tag property of each control 28
2.2.2 When using GUIDE, retain the automatic function names 28
2.2.3 When using GUIDE, use the handles structure carefully 28
2.3 Programming Conventions 28
2.3.1 Remember that MATLAB was developed to do math 29
2.3.2 Remember that for-loops in MATLAB differ than for-loops in C 29
2.4 Source Code Documentation 29
2.5 Error Checking and Debugging 29
3 C++ Coding Conventions 31
3.1 Source Code Organization 31
3.1.1 Match the name of the class to the name of the source files 31
3.1.2 Name the header files with care so that they don’t conflict 31
3.1.3 Use appropriate extensions for source files 31
3.1.4 Avoid hard-coded path names in source files 32
3.1.5 Include only those header files which are required 32
3.1.6 Declare functions and variables only in header files 32
3.1.7 Use the MFC Version Resource 32
3.1.8 Build debug and release executables to their respective subdirectories 32
3.2 Naming Conventions 33
3.2.1 Specify member variables of a class as “private” and follow camel notation 33
3.2.2 Consider a special prefix for member variables 33
3.2.3 Name static member variables using all caps 33
3.2.4 Prefix pointer variables with lowercase “p” 34
3.2.5 Use get and set property methods to access member variables 34
3.3 Programming Conventions 34
3.3.1 Use static member variables or constants rather than hard-coding numerical values 34
3.3.2 Terminate Case Blocks 35
3.3.3 Declare variables wherever they are used. 35
3.3.4 Initialize variables wherever they are declared 35
3.3.5 Place new and delete statements so as to emphasize their relationship with each other 36
3.3.6 Be vigilant about not accessing the pointer to an object which has been deleted 37
3.3.7 Avoid the use of macros unless they are absolutely necessary 37
3.3.8 When nesting conditions and loops, use curly braces to clarify the statements belonging to each condition 38
3.3.9 Conditionals in the “if” statement should be free of assignment operators. 38
3.4 Source Code Documentation 39
3.5 Error Checking and Debugging 39
3.5.1 Throw an exception only when required 39
3.5.2 A class should be left in a defined state in case of failure 40
4 C# Coding Conventions 41
4.1 Source Code Organization 41
4.2 Naming Conventions 41
4.3 Programming Conventions 41
4.4 Source Documentation 41
4.5 Error Checking and Debugging 41
5 Visual Basic Coding Conventions 43
5.1 Source Code Organization 43
5.2 Naming Conventions 43
5.3 Programming Conventions 43
5.4 Source Documentation 43
5.5 Error Checking and Debugging 43
6 Java Coding Conventions 45
6.1 Source Code Organization 45
6.2 Naming Conventions 45
6.3 Programming Conventions 45
6.4 Source Documentation 45
6.5 Error Checking and Debugging 45
Best Practices for All Languages
This section describes the general best practices for programming for the University of Houston College of Optometry, regardless of the programming languages. Cases from different languages are presented in examples to illustrate ideas, but the principles transfer to all languages. The reader can infer the language of each example from the syntax for the comment.
spatialFrequencyCpd=1.0; % percent sign for MATLAB
double spatialFrequencyCpd=1.0; // double-slash for C++, C# or Java
Dim spatialFrequencyCpd As Double = 1.0 ' single-quote for VB
Acknowledgements
This set of best practices was originally compiled by Raja Nadar, a UHCO employee. It is heavily based on coding conventions described by Macadamian Technologies Inc. which is a software engineering and consulting firm based in Ottawa, Canada. This set of conventions is also heavily influenced by a book titled Industrial Strength C++ by Mats Henricson, Erik Nyquist and Ellemtel Utvecklings. Other best practices have been inspired by observing common difficulties faced by novice programmers when Hope Queener supervised their projects.
1 General Source Code Organization
1 Use source code file names that reflects the content of the file
Use descriptive source code file names, such that the name reflects the unique content of the file. Source code file names are the first step in maintaining software. If the file name is ambiguous or cryptic, it can be difficult for a developer to see the purpose of the file when sharing or passing on code. The goal for the file names in a project is to present a general organization that is easily seen by looking at the contents of the source code folder. Sometimes, legacy file names are short because of the early limitations on file name length to 8 characters. This is true for much of the MATLAB library, and many file names used in the MFC library. Developers are no longer limited in this manner.
Consider for example a psychophysics program that performs a contrast sensitivity measurement that has the following separate modules:
• a user interface module for entering experiment information, including the test condition parameters
• a module responsible for drawing the visual stimuli
• a module responsible for controlling the sequence of the stimulus presentation and response collection
• a module that gets the response from the user interface device (button box)
• a module that writes the results to a text file
The following MATLAB file names would describe the organization above concisely.
CsfGui.m
CsfDrawStimulus.m
CsfExperiment.m
ButtonResponse.m
CsfResults.m
Note that the module “ButtonResponse” does not have Csf in the file name. This is because the module is not unique to the Csf experiment. It is a module written for general use with any experiment that needs the button box responses.
An example of vague or cryptic naming for the above modules would be:
main.m
draw.m
myexpt.m
button.m
file.m
2 Avoid spaces in file names
As much freedom as current developers have in naming source files, spaces in file names are not necessary and by convention, discouraged. Use mixed case to separate words in filenames. Underscores can be used sparingly to visually separate information in a folder name (such as an archive folder), but keep in mind that they are a bit awkward to type.
3 Avoid changing names of source code files to reflect versions
Maintain the same names of the source files in the project throughout the lifetime of development. Avoid names like “My”, “Final”, “Current”, “Recent” in file names and folder names. Add annotations regarding version or author to archived files, not to current project files.
SignalAnalysis.cpp // recommended
SignalAnalysisNew.cpp // avoid
SignalAnalysisFinal.cpp // avoid
SignalAnalysisHMQ.cpp // only in archive folder; delete from project
4 Avoid hard-coded path names to other source files
This convention applies to other source code files that a source files accesses. In general, set up the programming environment to be able to find the file without the path name being named explicitly in the source files. For example, if in a C++ file, a header file for a library function is used in an “#include” statement, the path to the header file should be defined in the Visual Studio project settings that control how the application is compiled rather than in the source file. For a MATLAB project, include toolbox folders in the MATLAB path or temporarily set the path to include folders that are not in a toolbox.
#include // recommended; uses project settings
#include "C:\Program Files\DCAMSDK\Include\DcamSdk.h" // avoid
Typically these library files (or toolbox files) are located in a default folder that was selected by the library installer program. If the project is copied to another developer’s system, the library files are expected to be in the same folder location on either system.
Sometimes, source files are organized in parallel folders within a project. For example, perhaps two projects share a set of files that are in a third folder. Imagine such a folder structure:
C:\...\Project\DiagnosticTools
C:\...\Project\Common
C:\...\Project\UserApplication
In this case, the projects located in the folders “UserApplication” and “DiagnosticTools” both use files located in “Common”. In this scenario, it is acceptable to use relative path notation to the files in the folder “Common”, with the assumption that these folders will retain their relative organization. This method can be easier than redefining all the project settings, which are typically full path names, when switching from one developer’s folder to another. Note that if the project structure changes, the source code will also have to be changed to reflect the new folder structure, so this method is an option, but not always the easiest to maintain.
#include "..\Common\ResultFile.h" // recommended; refer to peer folder
5 Develop and test as a least privileged user
Running as an administrative user routinely is not recommended from a security point of view. Since any of the users of software that we develop may be restricted users, our code must be usable by restricted users. Restricted users do not have write permission in the Program Files folder under Windows XP. Legacy code may have stored configuration files, which the user needs to write to the application folder (i.e. the “current folder” if no path name was specified) which is typically in the Program Files folder:
C:\Program Files\application-name.
If the developer does not test the code as a least privileged user, these kinds of restrictions go unnoticed during the development cycle. Also, running as a restricted user helps to insulate one’s computer system from malicious code, which may launch as the current user and then be unable to write to the system folders. For limited use, the OPT domain has a generic user name, “developer”, that can be set up as an administrative user with domain access on your development computer. Also, one can run a single application as an administrator, while continuing to be logged on as a restricted user, using the “Run As” function.
6 Maintain only project source files in the source code folder
One goal in maintaining source code archives is to keep the development folders compact and relevant. To support this goal, keep development folders free of obsolete source files, old copies of current source files, large data sets, etc. Any notes or test results that the developer wants to keep with the source files should be maintained as text or MS Office files that are clearly distinguishable from the source code modules. Sample data and results used by the application are best stored in a separate folder, so that archives do not fill up with images, movie files or other large data that is already backed up.
7 Maintain backup of development directories
Maintain backup of development directories either by using a version control system, or manually by retaining copies of the source code. One recommended version control system is the open source package “Subversion”:
For Windows developers, TortoiseSVN provides a convenient way to work with Subversion:
On any given day, a project may seem to move backwards instead of forwards. It can be time-saving to be able to start over from yesterday’s work when today’s progress is going poorly. Or, it may be useful to simply compare files between yesterday and today. It is also valuable to be able to recreate exactly what the code was doing during a particular release period. No code is “bug-free.” As issues are discovered, knowing when the issue was present can be important in determining how to salvage data collected during the bug-ridden time period. As to frequency of saving of versions, the rule of thumb is daily or after any milestone is reached.
Even with a version control system in place, it is also recommended to maintain backup copies of the code that you release to users (or for your own use for real data collection) on separate media such as an external backup drive or CD or DVD.
If a version control package is not available, make regular back up copies of the source folder. A preferred strategy is to copy the entire source code folder to the archive folder and append the folder name with a date code (as “_yyyymmdd”). This strategy is preferred to just saving the ‘changed’ files, because it is easy to lose track of how several modules work together. If the entire folder is saved, the entire project can be reconstructed at any point in time. If saving mid-day after a development milestone one can append “a” for an early save and then later use “b” for the end of day backup. Alternately, one might append notation that identifies the milestone. All folder notations are added only to the archive folder names, never in the current working folder. Keep the working folder clean.
To reduce bulk in archive folders resulting from Visual Studio projects, it can be helpful to delete the temporary files such as the Debug folder, the .pch (pre-compiled header files) files or .ncb files.
As an example of the manual naming strategy, consider a psychophysics program called “RSVP” (rapid serial visual presentation) used to measure reading speed under various conditions. The proposed directory structure could be:
Working folder: C:\...\RSVP
Mid-day backup: C:\...\RSVP_Archive\RSVP20060622.a
End-of-day day backup: C:\...\RSVP_Archive\RSVP20060622.b
Next day backup: C:\...\RSVP_Archive\RSVP20060623
First release backup: C:\...\RSVP_Release\RSVP20060419
Second release backup: C:\...\RSVP_Release\RSVP20060612
8 Back up files to another device or backup media
HARD DISKS DIE! Please do not assume that yours will not. At this writing, no backup server is in place for the Core Programming module. Use CDs, DVDs, external hard drives or other separate media for backups. Do NOT use the “Opt_Public” folder as a backup device. It is intended for moving data between computers conveniently, not for long-term storage.
If one maintains clutter-free source directories and deletes the intermediate files (especially the .pch or .ncb files), a CD can hold many backups of a project. It is critical to keep copies of source code for released projects, even if the releases are not quite ready for “real” data collection. If the research staff has access to a program, assume that they will collect and/or analyze some data with it.
9 Create an installer file for your application
This topic is applies to more complex projects, such as those developed by the Core Programming Module developers. When a MATLAB project consists of many m files, or a Visual Studio project requires supporting DLL files or configuration files, it can be very beneficial to create an installer package for distributing the application. For the MATLAB projects, the MATLAB compiler can be used to create an encrypted form of the application that can be distributed with the MATLAB runtime callable engine. Generally, under Windows XP, our custom C++ or C# applications are installed to the “Program Files” folder, but if your program needs any support files, such as DLLs or configuration files, the Visual Studio Installer (separate tool for 6.0, integrated in .net 2005) provides a way to put them in the appropriate directories and to be uninstalled with the Windows Installer (Control Panel: Add/Delete Programs).
If the user needs to have write-access to a file, do not put the file in the Program Files folder. Instead, install the file to the application data folder under the “All Users” folder and maintain a copy in the appropriate user’s folder at startup:
C:\Documents and settings\All Users\Application Data\application-name
2 General Naming Conventions
The naming conventions below assume that a developer has full control over the modules in the project. Often, we inherit a project with source files that followed some other convention or none at all.
If the conventions in existing modules were weakly enforced, developers are encouraged to make all new code follow the current conventions. If the prior conventions were uniformly enforced, developers should keep to the legacy convention, so that the entire project is consistent with itself.
It is left to the discretion of the developer whether to enforce new conventions or follow existing ones, but some convention should be followed consistently.
1 Use full, meaningful names for variables and functions
The purpose of a variable or function should be obvious from its name. The use of full, descriptive names enhances code. Many lines of legacy code contain cryptic names that require the developer to guess the information contained in the variable or the purpose of the function. Use correctly spelled, full words to describe variables and functions so that no interpretation is required. It may take more effort to type a longer, descriptive name, but with editing tools such as copy and paste and insertion editors, the work of doing so is manageable and worth the effort.
2 For variable names choose adjectives and nouns
When declaring variables (or function arguments), the quantity or object of interest can generally be described as a noun, modified by an adjective. Boolean variables are an exception and described separately, below.
backgroundStimulus=zeros(512,512); % recommended
bgstim=zeros(512,1512); % avoid; cryptic
appearStimulus=zeros(512,512); % avoid; verb
3 For variable names and function arguments use “camel” notation
In camel notation, the first word of the concatonated variable name is lowercase and subsequent words have the first character capitalized. Acronyms and abbreviations (used sparingly) only capitalize the first character, even if they are normally all capitals in written expressions.
double spatialFrequencyCpd; // recommended
double spatialFrequencycpd; // avoid
int imageHeightMm; // recommended
int imageHeightmm; // avoid
meanRms = 0; % recommended
meanRMS = 0; % avoid
4 For function names, use a strong verb followed by an object.
Functions and methods take some kind of action on data. Therefore, name them starting with a strong verb (action word) and the object of the action. Use the same verb for the same kind of operation. For example, use “compute” or “calculate” but not both within the same class. Be specific and include an adjective before the object name, where applicable. Some verbs cover just about any meaning. Avoid general names or vague names for functions or procedures.
ComputeZernikeCoefficients(); // recommended
SaveWavefrontImageFile(); // recommended
Opening(); // avoid (not a strong verb; too vague)
HandleCalculation; // avoid; vague
PerformServices(); // avoid; vague
For functions whose main purpose is returning the current condition, use “Is” as the verb. In the example below, the purpose of the function is to ask “Is the plot file valid?” The function name does not suggest that the file was opened or read, or that data from the file is available. The function may only check to make sure that the file exists and that it starts with some specific character sequence.
function [isFileValid]=IsPlotFileValid(plotFileName) % recommended
Note that a boolean return value does not always mean that the function should start with “is”. If the function returns a boolean value to indicate the status of the action taken by the function, the verb should represent the action taken. In the example below, the action taken is to open and read the parameter file. The return status indicates whether the operation was successful.
fileStatus = ReadParameterFile(CString parameterFileName);//recommended
Avoid the following. In the example below, the purpose of the function is ambiguous. Does the function ask if the file has already been opened? Does it open the file and return a status on the opening operation?
IsOpenParameterFile(CString parameterFileName); // avoid
5 For function or method names, use title (Pascal) case
Function names are comprised of words that are concatenated together to describe the operation of the function on the available data. The name should include enough words to describe the function specifically.
% recommended
function [zernikeResult] = ComputeZernikeCoefficients(centroids)
% avoid
function [z] = computezernikecoefficients(c); %avoid
function [zers] = compute_Zernike_coefficients(cents); %avoid
6 Boolean variables start with “is”
Boolean variables are used in two main contexts. In the first, a checkbox or other graphic user interface control selects an option as on (selected) or off. In the second context, the result of a function is Boolean, indicating the success or failure of the function. In either case, the leading “is” in the name cues the developer that the variable is true or false. Depending on the user interface development tools, other conventions may make more sense, however. The developer is encouraged to use his or her best discretion and apply a consistent practice when naming Boolean variables.
7 Name Boolean return arguments as true if the result is successful
When a function returns a Boolean value, the return status should be true when the function is successful. These variables are typically tested with “if” statements soon after the function call, to handle any subsequent dependencies. The name of the Boolean return argument should relate to the function name that produced it, but need not include the entire function name, if the meaning is easily understood. Begin these variable names with “is” and end with “Ok” or “Valid”.
isFileOk = ReadParameterFile(...); % recommended
isParameterSetValid = ValidateParameterSet(); % recommended
isError = ComputePsychometricFunction(); % avoid;
A function that was written prior to these conventions or outside of UHCO may return a true value in case of an error. If the result is truly Boolean, you can negate the result and still choose a “success” name for no error.
isCameraOpenOk = !cameraABC.Open (); % returns 0 (false) on success
If the result is zero for success and a numeric code for an error, use a different variable name such as “cameraOpenStatusCode”, and interpret all return conditions provided by the developer.
8 Name Boolean selection variables as “Selected” or “On”
Boolean variables are often necessary for user-selected options such as checkboxes. The checkbox control variable should be named consistently with the conventions of the language and development environment. Include a reference to the control type in the name of the control. For instance, “Check” or “Chk” is acceptable to append to all checkbox control names. Any variables not attached to the graphical user interface (GUI) that are initialized from the GUI (or a parameter file or a hard-coded default state) start with “is” followed by the “adjective”-“noun” pattern of other variables, followed by “Selected” or “On”. Avoid the user of “Enabled” in a Boolean variable name, unless referring to the enabled state of a GUI control. An option may be “on” and “disabled”, for instance, if a checkbox control is checked and the user is disabled from changing it.
isAdvancedProcessingSelected=advancedProcessingCk.value; % recommended
isFixationPointOn=TRUE; // recommended; may set default state
FixationPointEnabled=TRUE;// avoid;
9 Name constants using all capitals and underscores.
For constants, use the legacy C/C++ convention of using all capitals separating component words with underscores. This convention distinguishes static variables and constants from variables that can be modified.
const int MAXIMUM_MODES = 66; // number of Zernike modes(coefficients)
10 Use only well-accepted acronyms or abbreviations and do so sparingly.
Abbreviations and acronyms in variable names are acceptable so long as they are standardized (in general or in vision science and/or optics), such as mm, cm, cpd (cycles-per-degree), MTF, PSF, RMS. When the variable is declared, spell out the abbreviation in the comments. Even though the acronym may typically be shown as all capitals or all lowercase, capitalize the first character, such as “wavefrontMtf”. Do not use an abbreviation for an entire variable name.
double spatial FrequencyCpd; // recommended
double wavefrontRmsError; // recommended; root mean square error
cpd; // avoid
RMS; // avoid
11 Include units in variables representing physical quantities
If a variable name represents a physical quantity, the name should include units as the last word in the name. This practice is especially important when using several unit spaces in a program, such as centimeters, pixels and degrees of visual angle to describe the extent of a stimulus. Common abbreviations for units are acceptable.
temperatureDegreeC = 2.8; %recommended
temperatureRepresentedInDegreeCelsius =2.8; %avoid; excessive
temperatureDegreeF = 37.0;%recommended
temperature =37.0; %avoid – units are ambiguous
12 Use single-character variables sparingly and with clear purpose
In general, it is better to use a descriptive word such as “time” rather than “t” in an expression. However, if the single-character notation makes the mathematical notation more clear, or if the variable is used as an index, it can be appropriate. Keep in mind that MATLAB declares the meaning of many single characters such as “i” and “j” for the square root of -1.
timeStartMs = 0;
timeEndMs =1000;
t = [timeStartMs:timeEndMs]; % initialize time axis
signal=sine(2*pi*t/timeEndMs);
plot(t,signal);
13 Avoid arbitrary abbreviations in variable names
Hardware and compiler limitations enforced short variable names in the early years of programming. This constraint led to cryptic variable naming practices, such as cutting words short or leaving out the vowels. Avoid this outdated practice. Using full descriptive words brings the benefit of readability and ease of interpretation. For clarity use only commonly recognized abbreviations in variable names. Select a longer variable name if it enhances clarity.
int subjectCount; // recommended
int sbjctCnt; // avoid
double spatialFrequencyCpd; // recommended
double spatFreq; // avoid
14 Use “temp” in a variable only if it is truly temporary
When a variable is only computed for the sake of the next line of code, it can be appropriate to give it a prefix “temp” to make it clear that the variable is only used in the local situation for the purpose of computing a more permanent resulting variable. If declaring a variable name including “temp”, the variable should be used within the next couple of lines of code and not used again.
15 Avoid the use of underscores in variable or function names
In legacy code, the underscore was often used to separate words in descriptive variable or function names. Some older languages treated lowercase and uppercase as the same character. Modern languages are case sensitive, and therefore the camel and Pascal notation are used instead of inserting the underscore, which is awkward to type. Note also that identifiers beginning with an underscore or double underscore are reserved by the compiler in MS C++. If use of an underscore is warranted based on the convention of the development tools, follow the established convention.
double minimumFrequencyHz=1.0; // recommended
double minimum_frequency_hz; // avoid; underscores
double _minimumFrequencyHz; // avoid (leading underscore)
16 Avoid “Hungarian Notation”
Hungarian notation attaches a type prefix to the variable. This notation was promoted for some years by Microsoft in the era of Visual Studio 6.0, but has been abandoned with Visual Studio .net. Since the .net development environment checks types rigorously, this notation is not as critical. Avoiding Hungarian notation simplifies variable naming and avoids errors introduced when the type is changed but the developer forgets to change the name. If an existing project was written with Hungarian notation, however, continue to follow the practice in legacy projects.
bool isValidFile; // recommended
bool bIsValidFile; // avoid
int primeNumber; // recommended
int nPrimeNumber; // avoid
17 Avoid hard-coded path names in source files
Hard-coded path names render programs inflexible and potentially useless when the program is used on a computer that has a different folder structure. When loading a file in to your program, generally ask the user to supply the file name, use the application path (for read-only data), or use a configuration file that specifies the exact location of files. Configuration files can be initialized at installation time. If a default path must be supplied, identify the “My Documents” folder programmatically or use the “All Users” application data folder for the custom application. Be sure that a non-administrative user has write access to any path to which the program needs to write. For example, restricted users do not have access to the application folder under the “\Program Files” folder under Windows XP.
General Programming Conventions
1 Use static variables or constants rather than hard-coding values
Numerical constants like the maximum size of a data structure or mathematical constants such as ( (pi) should be declared as static member variables or constants. MATLAB does not provide a means to declare static or constant values, but it is still recommended that these types of values be set apart from variables by using the all-capitals naming convention.
MINIMUM_PUPIL_DIAMETER_MM=3; % recommended, used to check user input
#define PI = 3.1415926535897931; // recommended for legacy C++
static double PI = acos(-1.0); // recommended for static variable
pupilAreaSquareMm = PI*pupilRadiusMm*pupilRadiusMm;//recommended
double pupilAreaSquareMm=3.14159*pupilRadiusMm*pupilRadiusMm;//avoid
2 Avoid global variables
Global variables lead to complications that can easily be avoided by declaring all variables as members of a class or keeping the variables local to a function. In C++ or C#, use classes. In MATLAB pass data as arguments to functions and avoid using the global workspace or scripts.
3 Use loop or index variables consistently in your program
When looping through the same array, always use the same index name. For example, if looping through a matrix with index variables “row” and “column”, do not later use variables “xIndex” and “yIndex”. If using “i”, “j” and “k” as iterators on a three dimensional array, always use “i” for the same dimension of the array. Use the same type of name on different dimensions.
for (int row =0; row ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- validation verification and testing plan template
- best practices for developing customizations for microsoft
- harvard university information technology
- true false questions
- coding conventions for c and java applications
- coding theory in mathematica
- employment application
- section 508 compliance approach for web based applications
Related searches
- java coding projects for beginners
- java coding examples for beginners
- coding a simple hello world java program
- java applications with source code
- coding for vaccines and administration
- c to java translator
- c to java convertor
- c to java converter
- linear algebra and its applications pdf 5th
- linear algebra and its applications 5th pdf
- linear algebra and its applications solutions
- lay s linear algebra and its applications pdf