0% found this document useful (0 votes)
40 views

The Essence of Good Programming Practices

The document discusses good programming practices for engineering students using MATLAB, including modularity, generalization, and documentation. Modularity involves writing code in separate, reusable modules or functions. Generalization means writing flexible code that can handle variable parameters rather than being hardcoded. Documentation includes commenting code, using meaningful variable names, and specifying units. Following these practices leads to code that is easier to understand, modify, and debug. Exceptions may be made for time pressures but often lead to future issues.

Uploaded by

neeraj kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

The Essence of Good Programming Practices

The document discusses good programming practices for engineering students using MATLAB, including modularity, generalization, and documentation. Modularity involves writing code in separate, reusable modules or functions. Generalization means writing flexible code that can handle variable parameters rather than being hardcoded. Documentation includes commenting code, using meaningful variable names, and specifying units. Following these practices leads to code that is easier to understand, modify, and debug. Exceptions may be made for time pressures but often lead to future issues.

Uploaded by

neeraj kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

The Essence of Good Programming Practices

By Nathan Delson

Objective of Good Programming


Good Programming Methods
Modularity
Generalization
Documentation and Notation
Extra Comments About Matlab and Engineering Analysis
Exceptions to the Rules
Examples and Resources

Like an essay, a computer program can be written well or poorly. Developing good
programming skills will serve one well throughout ones career in engineering as well as
open doors to many other career opportunities. As with writing essays, there are many
opinions on how to write good code. This document presents a few points that I believe
highlight good programming approaches. Many of the points are relevant to all
programming languages, but the specific examples relate to Matlab, and are geared
towards MAE150, a course for Aerospace, Bioengineering, Mechanical, and Structural
Engineering students. There are other more in-depth books on the subject
(see Examples and Resources end of document).

Objective of Good Programming


• Programs that can be easily updated and modified.
• Programs that can be easily verified and debugged.
• Programs that can be easily understood by others (including author three
months after writing).
• Programs that run correctly and efficiently.

Good Programming Methods


• Modularity
• Generalization
• Documentation and Notation

Modularity
A module of a program is a function or separate file that is called from the main program.
In a well-written modular program, one module can be updated without requiring
changes in the other parts of the program.
Consider the print dialog box that appears from most Windows applications, as shown
below:

When a new printer is added to the computer, the programs that use the printer do not
have to be re-written. Instead the features of the new printer are automatically available
to all programs that access the dialog box. This ease of updating the program
functionality is due to the modularity of the program. The print drivers are written
separately than the calling program. To achieve this modularity care must be taken to
ensure that there is proper information flow between the calling program and the module
(e.g. printer features and data to be printed).
When should one write a separate module (Matlab function or script file)?
• When there are well defined separate functions of the program, one should
separate the modules of the program accordingly. For example, in a dynamic
simulation, one module should could calculate the dynamics of the system,
another module could perform the plotting for an animation, and another module
could define the parameters of the model.
• Whenever one finds repeated code, it probably makes sense to write this code in
a separate function. Otherwise, when a change is required in the code (and it
always is), one needs to make the exact change in numerous locations that,
which is in itself an error prone process.
• An added advantage of writing repeated code in a function is that the overall size
of the program is shorter, which can be important is running the code on a low
powered microprocessor with limited memory.
In general Matlab functions are considered better code than a script file. With a function,
the input and output arguments are clearly defined, so it can easily be discerned what
variables are modified within the function. Moreover, the same function could be reused
to operate on variables of different names.

Generalization
A generalizable piece of code is preferred over a code that can only be used for a
unique application. For example, code which fixes the number of links in a robot arm is
less useful than code where that number is variable and can be used for a wide range of
robot arms. Below are some examples:
• Never hardcode values into program. Instead define variables for such
parameters. For example, by defining the number of links on a robot as a
variable, it can easily be modified in a single location. As a link is added or
removed from the robot. It is best to locate the definition of all parameters in a
single location, so one can view all parameters at once (instead of having
surprises hiding deep within the code)
• Use arrays instead of sequentially numbered variables. If you find yourself
defining variables such as: link_1 and link_2, replace this with an array link(1)
and link(2). There are many advantages to using arrays:
o The number of elements can be easily adjusted
o One can write loops to perform repeated operations, rather than
rewriting code with different variable names
o Matlab has many matrix operations that take advantage of arrays.

Good Example Bad Example


% GOOD CODE % BAD CODE

% Define number of links as variable % The following code may be easy to start
% and use arrays when possible writing,
% but does not allow easy changes to
number of links or use of loops
nlink = 4; % number of links

disp(link_length_1);
% use loop to easily display link lengths
disp(link_length_2);
for ilink=1:nlink
disp(link_length_3);
disp(link_length(ilink));
disp(link_length_4);
end

% No code changes are required if the


value of nlink is changed.
% More importantly code corrections need
to be done in one location only

Documentation and Notation


The purpose of good documentation is so that the author of the code as well as others
can easily understand the program and avoid mistakes. If one starts with good habits, it
only takes a small amount of effort to use meaningful variables names and document the
code while one is writing it. However, it can be very difficult to improve documentation
and variable notation after the code has been written. Some pointers are below:
• Do not shy away from long or medium length variable names. It is much better to
be unambiguous in a variable name. Some good variable names are:
o spring_length_initial % initial spring length
o spring_length_cur % current spring length
o spring_length_ar % array of spring lengths
• Do not use the same variable name for multiple meanings.
• Be consistent in how one names variables. For example:
o Add the suffix “_ar” to variable names that are arrays
o Add the prefix “d” to designate derivatives
o Add the prefix “n” to indicate number of
• Document the code while you are writing it. The documentation does not have to
be length, but rather timely!
• Always specify the units of numbers, where they are being entered.

Good Example Bad Example


% GOOD DOCUMENTATION % BAD DOCUMENTATION

% Define system parameters % (bad: no short overview of code)


arm_length = 0.5; % arm length in meters length = 0.5; % (bad: no units!)
alpha = 25*pi/180; % angle of motion in a = 25; % (bad: variable name too short
radians and use of angles instead of radians)
dalpha = 0.1; % angular velocity in radians da = 0.1; % (bad: no units)
/ second time = 0.01; %(bad: ambiguous variable
time_step = 0.01; % seconds name)

% Calc new angle using Euler method % (bad: no short overview of code)
alpha_new = alpha + dalpha*time_step; a = a + da*time; % (bad: reuse of variable
name is confusing)

Extra Comments About Matlab and Engineering Analysis


• Always define angles in terms of radians inside the code. One can easily convert
to degrees before plotting output. Both trigonometric functions and instantaneous
velocity calculations operate on radians, so a variable defined in degrees can
cause numerous errors.
• Take advantage of the interpretative nature of Matlab. Run lines of code
separately to test them out and view all variables.
• Become familiar with the debugging tools; especially the keyboard command.
• The structure data type is very powerful in terms of organizing variables and
improving modularization.

Exceptions to the Rules


There are always exceptions to the rule. When one is working to optimize run time, there
is a temptation to give up on modularity or other practices. When there is time pressure
then it may be easier to write code that is less generalizable, to get the code out the
door. However, in general I recommend avoiding these temptations. Whenever I have
taken a shortcut on good programming practices, the results always seem to have come
back on bit me.
Examples and Resources
An example Matlab code that incorporates many of the guidelines presented here is
shown in The Introduction to Kinematic
Plotting(www.maelabs.ucsd.edu/mae150/mae150_resources)

Matlab Programming Style Guidelines by Richard Johnson is a valuable collection of


guidelines and tips. (www.datatool.com/MatlabStyle.pdf)

Additional References from Richard Johnson’s Guidelines

The Practice of Programming, Brian Kernighan and Rob Pike

The Pragmatic Programmer, Andrew Hunt, David Thomas and Ward


Cunningham

Java Programming Style Guidelines, Geotechnical Software Services

Code Complete, Steve McConnel - Microsoft Press

C++ Coding Standard, Todd Hoff

You might also like