Octave style guide: Difference between revisions

7,103 bytes added ,  20 December 2023
m
(Start page describing our style guide for Octave code.)
 
 
(34 intermediate revisions by 5 users not shown)
Line 11: Line 11:
=== Line Length ===
=== Line Length ===


Keep the length of source lines to 79 characters or less, for maximum
There is no fixed line length.  In general, strive for clarity and readability and use your own judgement.
readability in the widest range of environmentsThis is inherited from
 
the [https://www.gnu.org/prep/standards/standards.html#Formatting GNU Coding Standards].
Everyone has access to monitors with more than 80 columns, but even so, exceptionally long lines can be hard to readHowever, keeping code together on a line that is logically one unit does improve readability.


=== Indentation ===
=== Indentation ===
Line 19: Line 19:
Use only spaces, and indent 2 spaces at a time.
Use only spaces, and indent 2 spaces at a time.


We use spaces for indentation. Absolutely do not use tabs in your code.
Absolutely '''do not use tabs''' in your code. You should probably set your editor to emit spaces when you hit the tab key.
You should probably set your editor to emit spaces when you hit the tab key.
 
=== Whitespace ===
 
===== Function Calls =====
 
When calling functions, put spaces after commas and before the calling
parentheses, like this:
 
<pre>x = max (sin (y + 3), 2);</pre>
 
An exception are matrix or cell constructors:
 
<pre>
[sin(x), cos(x)]
{sin(x), cos(x)}
</pre>
 
Here, putting spaces after {{codeline|sin}}, {{codeline|cos}} would result in a
parse error.
 
===== Indexing Expressions =====
 
For indexing expressions, do ''not'' put a space after the
identifier (this differentiates indexing and function calls nicely).
The space after a comma is not necessary if index expressions are simple,
i.e., you may write
 
<pre>A(:,i,j)</pre>
 
but
 
<pre>A([1:i-1;i+1:n], XI(:,2:n-1))</pre>
 
===== Matrix Definition =====
 
When constructing matrices, prefer using the comma rather than the space to
distinguish between columns.
 
<pre>
  M = [1, 2, 3
      4, 5, 6];
</pre>
 
However, if the matrix is large or the indentation makes it clear then the comma
may be dropped.
 
<pre>
  prices = [ 1.01  2.02  3.03
            44.04 55.05  6.06];
</pre>
 
There is no need to include semicolons to define rows when a newline is used instead.
 
===== Arithmetic Operators =====
 
Do include spaces around all binary arithmetic operators, for example
 
<pre>
  x = 1 / (1 + y) ^ 2;
</pre>
 
An exception is for extremely simple expressions like
 
<pre>n+1</pre>
 
In particular, simple expressions used as an argument to a function or as part of an indexing expression usually look better without extra spacing.  For example, you may write
 
<pre>
  x(1:end-1)
</pre>
 
Another exception is for complex arithmetic expressions.  It ''may'' improve readability to omit spaces around higher precedence operators, for example
 
<pre>
  z = cat (dim, (x2.*y3 - x3.*y2), (x3.*y1 - x1.*y3), (x1.*y2 - x2.*y1));
</pre>
 
== Error messages ==
 
When you encounter an error condition, call the function {{codeline|error}}
(or {{codeline|print_usage}}).  The {{codeline|error}} and {{codeline|print_usage}} functions
do not return.
 
It is customary to prefix the error message with the name of the function that generated it.  For example:
 
<pre>error ("my_cool_function: input A must be a matrix");</pre>
 
Because the function call to {{codeline|error}} is one code unit, prefer keeping the message on one line even if the message itself is long.
 
Octave has several functions that produce error messages according to the Octave guidelines.  Consider using {{codeline|inputParser}}
and {{codeline|validateattributes}}.


== Naming ==
== Naming ==
Use lowercase names if possible.  Uppercase is acceptable for variable names consisting of 1-2 letters.  Do not use mixed case (a.k.a. CamelCase) names.
Function names must be lowercase.  Function names are global, so choose them wisely.


=== General naming functions ===
=== General naming functions ===
Line 28: Line 122:
=== Function names ===
=== Function names ===


For most public functions we are limited by Matlab compatibility.  Use
For most public functions we are limited by Matlab compatibility.  Use whatever name Matlab chose.
whatever name Matlab choose.
 
For functions that are not present in Matlab, favor the use of underscores.
For example, {{codeline|base64_decode}}, {{codeline|common_size}}, or {{codeline|compare_versions}}.


For functions that are not present in Matlab favour the use of underscores.
There are exceptions to this:
For example, {{codeline|base64_decode}}, {{codeline|common_size}}, or
{{codeline|compare_versions}}.  There are exceptions to this:


; Matching C functions
; Matching C functions
Line 42: Line 136:
=== Variable names ===
=== Variable names ===


Avoid reusing the names of other functions as local variable names.  For
example, avoid naming local variables {{codeline|abs}},
{{codeline|log}}, or {{codeline|pow}}.  These names might be used later to try to call the function of that name, but instead will refer to a local variable, leading to very confusing errors.
An exception is the use of {{codeline|i}} and {{codeline|j}} as loop indices.
If a function has nothing to do with complex arithmetic, it is common and
acceptable to use {{codeline|i}} and {{codeline|j}} as local variables in
for loops.
== Quoted Strings ==
Always use double quotes for strings and characters rather than the Matlab single quote convention. Both quote types are accepted by Octave, but double quoted strings are interpreted slightly differently (see [https://www.gnu.org/software/octave/doc/interpreter/Strings.html Strings] in the manual for details).
'''Do:'''
<pre>
a = "Hello, world";
b = "x";
disp ("This \"string\" contains a\nnewline");
</pre>
'''Don't:'''
<pre>
s = 'Hello, world';
if (x(1) == 'c')
  disp ('Don''t quote one character this way, even if you''re a C programmer');
endif
</pre>
There are a few edge cases where single quoted strings may be preferable, and are permitted as exceptions under this style guide.
; String containing double quotes
: A string that contains many double quote characters itself, where escaping all of them with backslashes becomes inconvenient, may be easier with single quotes.
; String containing backslashes
: A string that contains literal backslashes, in particular a regular expression pattern, where doubly escaping certain character sequences is both inconvenient and harder to read, is usually better done with single quotes.
; Argument interpreted differently
: A string argument to the regexp family of functions may be interpreted differently depending on whether it is a double quoted or single quoted string. Certain escape sequences are interpreted only in a single quoted string for Matlab compatibility.
== ending blocks ==
Always use a specific end-of-block statement (like {{codeline|endif}},
{{codeline|endswitch}}) rather than the generic {{codeline|end}}.
Enclose the condition of an {{codeline|if}}, {{codeline|while}}, {{codeline|until}}, or
{{codeline|switch}} statement in parentheses, as in C:
<pre>
if (isvector (a))
  s = sum (a);
endif
</pre>
Do not do this, however, with the iteration counter portion of a {{codeline|for}}
statement.  Write:
<pre>
for i = 1:n
  b(i) = sum (a(:,i));
endfor
</pre>
== ! operator ==
* The Octave operator <code>!</code> should be used for logical negation, rather than <code>~</code>.
* The negation operator is written with a space between the operator and its target, e.g., <code>! A</code>.
* For comparisons use <code>!=</code> instead of <code>~=</code>.


== Comments ==
== Comments ==
Line 47: Line 208:
=== # or % ===
=== # or % ===


Always use {{Codeline|#}} to write comments.
Always use {{Codeline|#}} to write comments for Octave code.  Only use {{Codeline|%}} if code must run in a dual Matlab/Octave environment.


Absolutely do not use {{codeline|%#}} or mix {{codeline|%}} and {{codeline|#}}
Absolutely do not use {{codeline|%#}} or mix {{codeline|%}} and {{codeline|#}}
Line 56: Line 217:
Use a single {{codeline|#}} for inline comments.  Use double {{codeline|##}}
Use a single {{codeline|#}} for inline comments.  Use double {{codeline|##}}
for block comments.
for block comments.
Comments that start with a single sharp-sign, {{codeline|#}}, are used to explain
the code on the same line as the comment itself.  These comments should
all be aligned to the same column to the right of the source code.  In
the Emacs mode for Octave, the {{codeline|M-;}} (@code{indent-for-comment})
command automatically inserts such a {{codeline|#}} in the right place, or
aligns such a comment if it is already present.  Example:
<pre>
C = 2 * pi * r;    # formula for circumference of a circle
</pre>
Comments that start with a double sharp-sign, {{codeline|##}}, are stand-alone
comments that occupy an entire line.  These comments should be aligned to
the same level of indentation as the code.  Such comments usually
describe the purpose of the following lines or the state of the program
at that point.  Example:
<pre>
## Calculate area and volume of a sphere
A = 4 * pi * r^2;
V = 4/3 * pi * r^3;
</pre>


=== Commenting out code ===
=== Commenting out code ===
Line 61: Line 245:
Do not comment code out.  If the code is no longer used, remove it.  We use
Do not comment code out.  If the code is no longer used, remove it.  We use
version control, we can always bring it back.
version control, we can always bring it back.
=== %! for test and demo blocks ===
Any demos or Built-In Self Tests (BIST) using the {{codeline|%!demo}} or
{{codeline|%!test}} syntax should begin two lines after the {{codeline|endfunction}}
keyword.  Demo blocks should be listed before test blocks.
See the section Writing tests on the [[Tests]] page.
=== FIXME notes ===
The preferred comment mark for places that may need further attention is
with {{codeline|FIXME:}} comments.
[[Category:Development]]
1,072

edits