Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant...

22
Feb. 9, 2010 Feb. 9, 2010 UHCO Graduate Course in MATLA UHCO Graduate Course in MATLA B Core Programming Module Core Programming Module Best Practices Best Practices Core Grant Programming Module Core Grant Programming Module Best Practices (Coding Best Practices (Coding Conventions) Conventions) General Best Practices General Best Practices MATLAB Best Practices MATLAB Best Practices

Transcript of Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant...

Page 1: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

Core Programming ModuleCore Programming ModuleBest PracticesBest Practices

Core Grant Programming ModuleCore Grant Programming Module

Best Practices (Coding Conventions)Best Practices (Coding Conventions)

General Best PracticesGeneral Best Practices

MATLAB Best PracticesMATLAB Best Practices

Page 2: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

AcknowledgementsAcknowledgements

Originally compiled by Raja Nadar (an RA Originally compiled by Raja Nadar (an RA from Computer Science) and Hope from Computer Science) and Hope QueenerQueener– Macadamian Technologies Inc., a software Macadamian Technologies Inc., a software

engineering and consulting firm based in engineering and consulting firm based in Ottawa, Canada. Ottawa, Canada.

– Industrial Strength C++ Industrial Strength C++ by Mats Henricson, by Mats Henricson, Erik Nyquist and Ellemtel Utvecklings.Erik Nyquist and Ellemtel Utvecklings.

Page 3: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

Core Grant Core Grant Programming ModuleProgramming Module

Programming Module of the NIH Core Center Programming Module of the NIH Core Center Grant: P30 EY007551Grant: P30 EY007551Core Center Grants provide infrastructure Core Center Grants provide infrastructure support for research centers that include NIH support for research centers that include NIH funded investigatorsfunded investigatorsOne of 4 ModulesOne of 4 Modules– Instrument Design, Biostatistics, Imaging, Instrument Design, Biostatistics, Imaging,

ProgrammingProgramming

Hope Queener is Principal of Programming Hope Queener is Principal of Programming ModuleModule

Page 4: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

Best PracticesBest Practices

Conventions for writing softwareConventions for writing software

Avoid typical pitfalls Avoid typical pitfalls

Strategies for long-term maintenanceStrategies for long-term maintenance

Provide consistency for single developerProvide consistency for single developer

Provide consistency between developersProvide consistency between developers

Page 5: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best Practices

Source Code Organization Source Code Organization

Naming Conventions Naming Conventions

Programming ConventionsProgramming Conventions

Source Code DocumentationSource Code Documentation

Error Checking and Debugging Error Checking and Debugging

Page 6: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best Practices Source Code Organization Source Code Organization

Give source code (.m) files meaningful namesGive source code (.m) files meaningful names

Add “version” notes to archives of files, not your working Add “version” notes to archives of files, not your working copycopy– work with: StereoStimulus.mwork with: StereoStimulus.m– store old versions as: StereoStimulus20080207.mstore old versions as: StereoStimulus20080207.m– avoid adding words like “final” or “old” to a file nameavoid adding words like “final” or “old” to a file name– if using several files, copy all to an archive folder if using several files, copy all to an archive folder

Avoid hard-coded path names in source filesAvoid hard-coded path names in source files– use uiputfile and uigetfile to let the user select the filesuse uiputfile and uigetfile to let the user select the files

Page 7: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best Practices Source Code Organization Source Code Organization (continued)(continued)

Maintain only project source files in the source Maintain only project source files in the source code foldercode folder– Copy old versions of files to archive foldersCopy old versions of files to archive folders– Maintain extensive data in a separate folderMaintain extensive data in a separate folder– Maintain separate folders for projectsMaintain separate folders for projects

Maintain daily backup development foldersMaintain daily backup development folders– StereoStimulusArchive\20100209StereoStimulusArchive\20100209– What did I do yesterday when everything worked?What did I do yesterday when everything worked?

Back up files to another device or backup mediaBack up files to another device or backup media

Page 8: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best Practices Naming Conventions Naming Conventions

Use full, meaningful names for variables and functionsUse full, meaningful names for variables and functionsFor variable names choose adjectives and nouns.For variable names choose adjectives and nouns.– spatialFrequencyspatialFrequency

For variable names and function arguments use “camel” For variable names and function arguments use “camel” notationnotationFor function names, use a strong verb followed by an For function names, use a strong verb followed by an object.object.– PrepareStimulus(stimulusParameters)PrepareStimulus(stimulusParameters)

For function or method names, use title (Pascal) caseFor function or method names, use title (Pascal) caseNote that MATLAB help shows a different naming Note that MATLAB help shows a different naming convention, but by using a different one it is easier to convention, but by using a different one it is easier to distinguish user-defined variables and functionsdistinguish user-defined variables and functions

Page 9: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best Practices Naming Conventions Naming Conventions (continued)(continued)

Use consistent naming patterns for similar Use consistent naming patterns for similar operationsoperations– Choose Choose oneone: compute, calculate, or find: compute, calculate, or find

Include units in variables representing Include units in variables representing physical quantities (pixels, mm, Hz, ms)physical quantities (pixels, mm, Hz, ms)Use “temp” in a variable only within short Use “temp” in a variable only within short blocks of codeblocks of codeAvoid the use of underscores in variable or Avoid the use of underscores in variable or function names (awkward to type)function names (awkward to type)

Page 10: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best Practices Naming Conventions Naming Conventions (continued)(continued)

Use only well-accepted acronyms or Use only well-accepted acronyms or abbreviations and do so sparingly.abbreviations and do so sparingly.

Avoid arbitrary abbreviations in variable namesAvoid arbitrary abbreviations in variable names– Keep all the vowelsKeep all the vowels– The longer name is much easier to understand for the The longer name is much easier to understand for the

poor soul that inherits your codepoor soul that inherits your code

Use single-character variables sparingly and Use single-character variables sparingly and with clear purposewith clear purpose– use (row, col) rather than (i, j) or (x, y)use (row, col) rather than (i, j) or (x, y)

Page 11: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best Practices Programming Conventions Programming Conventions

Avoid hard-coding valuesAvoid hard-coding values– Store fixed values in a variable, and use the variableStore fixed values in a variable, and use the variable

trialCount = 10; trialCount = 10; ……(other initialization code)…(other initialization code)…for trial = 1:trialCount for trial = 1:trialCount ……rather thanrather thanfor trial = 1:10for trial = 1:10

– Obtain values from the available files and user input, Obtain values from the available files and user input, rather than hard-codingrather than hard-coding

reply = inputdlg(‘Enter the number of trials’);reply = inputdlg(‘Enter the number of trials’);if isempty(reply), return;if isempty(reply), return;else trialCount = str2num(char(reply{1}))else trialCount = str2num(char(reply{1}))endend

Page 12: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best Practices Programming Conventions Programming Conventions (continued)(continued)

Avoid global variablesAvoid global variables– The global keyword should be avoidedThe global keyword should be avoided– Global variables are rarely needed and make Global variables are rarely needed and make

code harder to maintain and reusecode harder to maintain and reuse

Declare one variable per lineDeclare one variable per line

Use loop or index variables consistently in Use loop or index variables consistently in your program (same variable for same your program (same variable for same purpose)purpose)

Page 13: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best Practices Programming Conventions Programming Conventions (continued)(continued)

Handle all possible conditions in a conditional statementHandle all possible conditions in a conditional statementif exist('fittype') % curve-fitting toolbox [threshold, goodnessOfFit] =

FitWithCurveFittingToolbox(stimulusLevels, percentCorrect);elseif exist('lsqcurvefit');% optimization [threshold, goodnessOfFit] =

FitWithOptimizationToolbox(stimulusLevels, percentCorrect);else msgbox('No suitable fitting toolbox available'); threshold = 0; goodnessOfFit = 0;end

– ““switch, case, otherwise, end”switch, case, otherwise, end”

Page 14: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best Practices Programming Conventions Programming Conventions (continued)(continued)

Handle all possible conditions in a conditional statementHandle all possible conditions in a conditional statementswitch (customerRanking) case {'1'} TransferToSeniorCustomerRepresentative(customerRanking) case {'2'} TransferToMidlevelCustomerRepresentative case {'3'} TransferToEntryLevelCustomerRepresentative case {'4', '5'} % service was satisfactory ReturnToMainPhoneMenu return ; otherwise RecordConfusedCustomerRanking(customerRanking) TransferToSeniorCustomerRepresentative(customerRanking)end

Page 15: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best Practices Programming Conventions Programming Conventions (continued)(continued)

Maintain a consistent layout style.Maintain a consistent layout style.For long expressions, put separate conditions on For long expressions, put separate conditions on separate linesseparate lines– Use MATLAB ... syntax to extend a statement to Use MATLAB ... syntax to extend a statement to

multiple linesmultiple lines

Compare numeric values from lowest to highest Compare numeric values from lowest to highest to mimic math expressionsto mimic math expressions– ((0 < column) & (column < imageWidth))((0 < column) & (column < imageWidth))

Indent argument lists for functions that wrap to Indent argument lists for functions that wrap to the next linethe next line

Page 16: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best Practices Programming Conventions Programming Conventions (continued)(continued)

When you start to copy and paste a block When you start to copy and paste a block (multiple lines) of code:(multiple lines) of code:– Consider redundancy: Am I doing something Consider redundancy: Am I doing something

that could be in a loop?that could be in a loop?– Consider a new function: Are the two blocks Consider a new function: Are the two blocks

identical except for a few parameters?identical except for a few parameters?

Aim for source code modules of less than Aim for source code modules of less than 1000 lines (less is better)1000 lines (less is better)

Page 17: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best PracticesDocumentation (Comments)Documentation (Comments)

Include an introduction comment at the top of Include an introduction comment at the top of the source file: author, date, purposethe source file: author, date, purposeInclude copyright information, if applicableInclude copyright information, if applicableIf variable names and functions are self-If variable names and functions are self-describing, commenting can be minimaldescribing, commenting can be minimal– Comment on the purpose of a conditional block of Comment on the purpose of a conditional block of

code or a loop, if not obviouscode or a loop, if not obvious– Use brief comments at the start of a function.Use brief comments at the start of a function.– Comment on the function’s limitationsComment on the function’s limitations

Document the source of algorithms that are usedDocument the source of algorithms that are used

Page 18: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best PracticesError Checking/Debugging Error Checking/Debugging

Check the arguments that come in to a functionCheck the arguments that come in to a functionUse messages to signal code that should never Use messages to signal code that should never be executed (if/then/else or switch/case)be executed (if/then/else or switch/case)Detect and handle an error that affects the rest Detect and handle an error that affects the rest of a routineof a routine– return status from functions that others depend uponreturn status from functions that others depend upon

Remember that error handling code is Remember that error handling code is vulnerable to errorsvulnerable to errorsUse meaningful, polite and grammatically correct Use meaningful, polite and grammatically correct messagesmessages

Page 19: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

MATLAB Best PracticesMATLAB Best PracticesSource Code OrganizatonSource Code Organizaton

Use functions rather than scriptsUse functions rather than scripts

Use separate m-files for generic Use separate m-files for generic operationsoperations

Keep specific functions in the same m-file Keep specific functions in the same m-file that calls themthat calls them

Add only general toolboxes to the Add only general toolboxes to the MATLAB pathMATLAB path– avoid building up many folders in pathavoid building up many folders in path

Page 20: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

MATLAB Best PracticesMATLAB Best PracticesNaming ConventionsNaming Conventions

Use general conventions, usuallyUse general conventions, usually

When using GUIDEWhen using GUIDE– rename the tag property of each controlrename the tag property of each control– retain the automatic function namesretain the automatic function names– use the handles structure carefullyuse the handles structure carefully

Page 21: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

MATLAB Best PracticesMATLAB Best PracticesProgramming ConventionsProgramming Conventions

Remember that MATLAB was developed to do Remember that MATLAB was developed to do mathmath– Use vectors and matrices rather than loopsUse vectors and matrices rather than loops– MATLAB examples read like math papersMATLAB examples read like math papers

““for” loops: MATLAB & C/C++for” loops: MATLAB & C/C++– C loops increment a variableC loops increment a variable– MATLAB loops operate for each item in listMATLAB loops operate for each item in list

““switch/case” loops: MATLAB & C/C++switch/case” loops: MATLAB & C/C++– C case statements require ‘break’ statementC case statements require ‘break’ statement– MATLAB case statements do notMATLAB case statements do not

Page 22: Feb. 9, 2010 UHCO Graduate Course in MATLAB Core Programming Module Best Practices Core Grant Programming Module Best Practices (Coding Conventions) General.

Feb. 9, 2010Feb. 9, 2010 UHCO Graduate Course in MATLABUHCO Graduate Course in MATLAB

General Best PracticesGeneral Best PracticesHope’s FavoritesHope’s Favorites

Add “version” notes to archives of files, not your Add “version” notes to archives of files, not your working copy working copy Maintain daily backup development foldersMaintain daily backup development foldersBack up to other mediaBack up to other mediaAvoid hard-coded path names in source filesAvoid hard-coded path names in source filesAvoid hard-coding values: use variablesAvoid hard-coding values: use variablesUse full, meaningful names for variables and Use full, meaningful names for variables and functionsfunctionsConsider before you start to copy and paste a Consider before you start to copy and paste a block of codeblock of code