Developing Robust MATLAB Code and Applications · 4 Make it run MATLAB Toolbox Packaging: Manages...

Preview:

Citation preview

1© 2015 The MathWorks, Inc.

Developing Robust MATLAB

Code and Applications

Paul Peeling

2

Good code is … Bad code is …

3

Agenda

Make it run

Clean up after yourself

Throw nice errors

Check your inputs

Choose good variable names

Test as you go

Measure your code

Write code faster

Build a system

Track what you did

4

Make it run

MATLAB Toolbox Packaging:

Manages the MATLAB search path

Picks up file dependencies

Specifies MathWorks product dependencies

Provides registration points for examples

Checks if you are installed

See future Developer Zone posts

http://blogs.mathworks.com/developer/

5

Clean up after yourself (Don’t pollute)

How to clean up

Options for clear

onCleanup

Graphics: figures and axes

How to start from a clean environment (for testing)

The MATLAB preference directory

MATLAB path management

Add-ons

startup.m

6

Throw nice errors

Types of error

Silent wrong answer

Why use identifiers?

MException.last

try / catch

dbstop if error

errordlg

7

Check your inputs

What if we don’t?

isempty isnan isfinite

isa …

narginchk

nargoutchk

validateattributes

validatestring

inputParser

Property type validation

8

Choose good names

Naming conventions

Finding variable usage

Renaming variables and functions

Ambiguous variable names

– for loop indices

– Case sensitivity

– i, j, l, ans

– load and eval

http://blogs.mathworks.com/videos/2010/03/08/top-10-matlab-code-practices-

that-make-me-cry/

9

Write tests

Class-based tests

Setup and Teardown

Positive and Negative Tests

Running tests

10

Measure your code

Static methods

– Code Analyzer

– TODO/FIXME

– Code Complexity

Dynamic methods

– Profiling

– Coverage

– Dependencies

11

Write code faster

Quick Access Shortcuts

Auto-indentation

Code folding

Code snippets

Navigating around code

12

Build a System

Cohesion

The Principle of Least Surprise

Packages

Naming Conventions

Relative File Locations

Lists of Arguments

Design Patterns

13

Track what you did

Version Control – What to Know

Doing a Comparison

Continuous Integration

“The Cat ate my Source Code”

14

Calls To Action

1. Use toolbox packaging

2. Use onCleanup

3. Rename variables

4. Write a test to fix a bug

5. Use version control

Recommended Reading

– MathWorks Developer Zone Blogs

– Software Development Classics

Recommended