The purpose of this guide is clarity. It goal is to produce code that is understandable, sharable, and maintainable. Well-written programs have fewer errors and are easier to debug and modify.
The goal is for all code to follow the same rules, such that it is easy to understand and appears as if only one person wrote all of the code (even though many people did).
▢ Use Matlab M-Lint Code Check Report
Be sure to run Matlab M-Lint Code Check Report to help identify potential errors and problems, as well as opportunities for improvement in your M-files.
▢ Do not use magic numbers. Numbers that are subject to change should be named as a variable or a constant.
Magic numbers are numbers that appear directly in computations. The use of magic numbers obscures the designer's intent in choosing that number, increases possibilities for error, and makes it more difficult to extend and adapt code in the future. Magic numbers should be replaced with constants or variables to make the program easier to maintain, understand, and read.
Use
studentsPerClass = 15;
students = nClasses * studentsPerClass;
Avoid
students = nClasses * 15;
▢ Floating point constants should always be written with a digit before the decimal point.
Use THRESHOLD = 0.5;
Avoid THRESHOLD = .5;
Make your code as readable as possible.
Martin Fowler: “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
Use parentheses.
Parantheses help clarify operator precedence.
Be careful of floating point comparisons.
Here is an example. You can use the round or eps function in Matlab to deal with these issues.
shortSide = 3;
longSide = 5;
otherSide = 4;
longSide^2 == (shortSide^2 + otherSide^2)
ans = 1
scaleFactor = 0.01;
(scaleFactor*longSide)^2 == ((scaleFactor*shortSide)^2 + …
(scaleFactor*otherSide)^2)
ans = 0
Consistency is very important in naming. The style of a name immediately indicates what the entity is: a function, variable, constant, etc...
▢ Use as descriptive a name as possible. Variables should be nouns, while functions should be "command" verbs.
Do not try to save horizontal space, as it is far more important to make your code immediately understandable to a reader.
Use numErrors or numCompletedConnections.
Avoid n, nerr.
Function names should be imperative (that is they should be commands).
Use OpenFile(.)
▢ Names of dimensioned variables and constants should usually have a units suffix.
Adding unit suffixes helps to avoid confusion
incidentAngleRadians
▢ Make sure there are no abbreviations in names.
Use whole words to reduce ambiguity.
Use compute_arrival_time(.)
Avoid comp_arr(.)
Specific phrases that are natural known through abbreviations should be kept abbreviated. Even these cases might benefit from a defining comment at their first appearance.
cm
▢ Names should be pronounceable and in English.
Pronounceable names are easier to remember.
▢ Names of functions should be written in lower case.
Filenames should be all lowercase and can include underscores.
Examples of acceptable file names:
my_useful_class.m
▢ The prefix is should be used for boolean functions.
is_overpriced(.); is_complete(.)
There are a few alternatives to the is prefix that fit better in some situations. These include the
has, can and should prefixes:
hasLicense(.); canEvaluate(.); shouldSort(.);
Functions should have meaningful names.
Make your filenames very specific. For example, use http_server_logs.m rather than logs.m.
Use compute_total_width.m not compwid.m.
An exception is use of abbreviations or acronyms widely used.
Functions with such short names should always have the complete words in the first header
comment line for clarity.
Functions with a single output can be named for the output.
Examples are mean(.), standard_error(.).
Functions with no output should be named for what they do.
An example is plot(.).
The prefixes get/set should generally be reserved for accessing an object or property.
getobj(.); set_application_data(.)
The prefix find can be used in methods where something is looked up.
find_oldest_record(.); find_heaviest_element(.);
Complement names should be use for complement operations.
get/set, add/remove/create/destroy, start/stop, insert/delete, increment/decrement, old/new, begin/end, first/last, up/down, min/max, next/previous, open/close, show/hide, suspend, resume, etc...
The names of variables should document their meaning or use.
▢ Variables names should be in mixed case starting with lower case.
linearity, credibleThreat, qualityOfLife
▢ The prefix n should be used for variables representing the number of objects.
nFiles, nSegments
▢ The suffix Array should be used for the pluralization of a variable.
pointArray
▢ Variables representing a single entity number can be suffixed by Number.
tableNumber, employeeNumber
▢ Iterator variables should be named or prefixed with i, j, k etc.
for iFile = 1:nFiles
:
end
▢ Avoid the use of i and j for scratch variables.
i and j are Matlab constant reserved for the squareroot of -1.
For nested loops, the iterator variables should be in alphabetical order
for iFile = 1:nFiles
for jPosition = 1:nPositions
:
end
:
end
▢ Avoid negated boolean variables
Use isFound not isNotFound
▢ Acronyms, even if normally uppercase, should be mixed or lower case.
Use html, isUsaSpecific, checkTiffFormat()
Avoid hTML, isUSASpecific, checkTIFFFormat()
Variables with a large scope should have meaningful names. Variables with a small
scope can have short names.
Scratch variables used for temporary storage or indices can be kept short. A programmer reading such variables should be able to assume that its value is not used outside a few lines of code. Common scratch variables for integers are ind, k, m, n and for doubles x, y and z.
The names of variables should document their meaning or use.
▢ Variables names should be in mixed case starting with lower case.
linearity, credibleThreat, qualityOfLife
▢ The prefix n should be used for variables representing the number of objects.
nFiles, nSegments
▢ The suffix Array should be used for the pluralization of a variable.
pointArray
▢ Variables representing a single entity number can be suffixed by Number.
tableNumber, employeeNumber
▢ Iterator variables should be named or prefixed with i, j, k etc.
for iFile = 1:nFiles
:
end
▢ Avoid the use of i and j for scratch variables.
i and j are Matlab constant reserved for the squareroot of -1.
For nested loops, the iterator variables should be in alphabetical order
for iFile = 1:nFiles
for jPosition = 1:nPositions
:
end
:
end
▢ Avoid negated boolean variables
Use isFound not isNotFound
▢ Acronyms, even if normally uppercase, should be mixed or lower case.
Use html, isUsaSpecific, checkTiffFormat()
Avoid hTML, isUSASpecific, checkTIFFFormat()
Variables with a large scope should have meaningful names. Variables with a small
scope can have short names.
Scratch variables used for temporary storage or indices can be kept short. A programmer reading such variables should be able to assume that its value is not used outside a few lines of code. Common scratch variables for integers are ind, k, m, n and for doubles x, y and z.
▢ Eliminate code duplication. Any block of code appearing in more than one m-file should be considered for packaging as a function.
It is much easier to manage changes if code appears in only one file. Do not copy and paste blocks of code. Instead, create a new function or subfunction of this block of code.
▢ Write a test script for every function. Use the prefix test_ for your test function and make use of the assert function.
Write a test script for every function. This practice will improve the quality of the initial version
and the reliability of changed versions. Consider that any function too difficult to test is probably too difficult to write. Boris Beizer: “More than the act of testing, the act of designing tests is one
of the best bug preventers known.”
For example, to test the function fibonacci, you should write
function test_fibonacci
Make use of the assert function.
▢ Functions should be kept short (guideline of under 30 lines of code). Modularize.
Modularization enhances readability, understanding and testing by reducing the amount of text which must be read to see what the code is doing. Code longer than two editor screens is a candidate for partitioning. Small well designed functions are more likely to be usable in other applications.
Make Interactions clear.
A function interacts with other code through input and output arguments and global variables. Structures can be used to avoid long lists of input or output arguments.
Partitioning.
All subfunctions and many functions should do one thing very well.
Every function should hide something.
Use existing functions.
It may be quicker or surer to find an existing function that provides some or all of the required functionality. For Matlab code, look on Matlab Central to see if an someone has already written a similar function, http://www.mathworks.com/matlabcentral/
Subfunctions
A function used by only one other function should be packaged as its subfunction in the same file. This makes the code easier to understand and maintain.
Make input and output modules.
Localizing the code that deals with them improves maintainability. Avoid mixing input or output code with computation, except for preprocessing, in a single function. Mixed purpose functions are unlikely to be reusable.
Format output for easy use.
If the output will most likely be read by a human, make it self descriptive and easy to read.
If the output is more likely to be read by software than a person, make it easy to parse.
If both are important, make the output easy to parse and write a formatter function to produce a human readable version.
▢ Variables should not be reused unless required by memory limitation.
Make sure concepts are represented uniquely.
Consider documenting important variables in comments near the start of the file.
It is standard practice in other languages to document variables where they are declared.
% pointArray Points are in rows with coordinates in columns.
Consider documenting constant assignments with end of line comments.
This gives additional information on rationale, usage or constraints.
THRESHOLD = 10; % Maximum noise level found by experiment.
Use of global variables should be minimized.
Vectorize in Matlab
If you can program the same operations without the use of a for loop, then the code should run a lot faster.
▢ Loop variables should be initialized immediately before the loop.
This improves loops speed and prevents bogus values if the loop does not execute for all possible indices.
result = zeros(nEntries,1);
for index = 1:nEntries
result(index) = foo(index);
end
▢ The use of break and continue in loops should be minimized.
Only use these if they have higher readability than their structured counterpart
▢ The end lines in nested loops can have comments
Adding comments at the end lines of long nested loops can help clarify which statements are in
which loops and what tasks have been performed at these points.
▢ Complex conditional expressions should be avoided. Introduce temporary logical variables instead.
Do not use
if (value>=lowerLimit)&(value<=upperLimit)&~ismember(value,...
valueArray)
:
end
but use
isValid = (value >= lowerLimit) & (value <= upperLimit);
isNew = ~ismember(value, valueArray);
if (isValid & isNew)
:
end
▢ The usual case should be put in the if-part and the exception in the else-part of an if-else statement. Avoid using the conditional expression if 0.
▢ A switch statement should include the otherwise condition. A switch statement should usually be a string.
For example,
switch (condition)
case ABC
statements;
case DEF
statements;
otherwise
statements;
end
▢ Use 2 spaces for indentation.
Do not use tabs in your code. You should set your editor to emit spaces when you hit the tab key.
▢ Keep the line length to a maximum of 80 characters long.
This is a traditional standard.
▢ Lines should be split at graceful points. Use alignment to enhance readability.
Split lines should occur
after a comma or space
after an operator
Align the new line with the beginning of the expression on the previous line
You can use OPTION + ; to insert an ellipsis on Mac, and
ALT + 0113 on Windows
totalSum = a + b + c + …
d + e;
function (param1, param2,…
param3)
▢ Short single statement if, for, or while statements can be written on line line.
if(condition), statement; end
while(condition), statement; end
for iTest = 1:nTest, statement; end
Semicolons usually have no space before them.
n = 1;
Colons have no space surrounding them.
for n = 1:10
:
end
Assignment variables have spaces around them.
n = 1;
Binary operators usually have spaces around them, but it's okay to remove whitespace around factors
v = w * x + y / z;
No spaces separate unary operators and their arguments.
x = -5;
if (x && !y) ...
There is no white space to the right of a ( and to the left of a ).
simpleAverage = (firstTerm + secondTerm) / two;
Commas are separated by a space.
foo(alpha, beta, gamma)
Never put trailing whitespace.
Minimize use of vertical white space.
Don't use blank lines when you don't have to. Logical groups of statements within a block should be separated by one blank line.