Lesson 6.3 – Writing Better Code

Learning Objectives

After reading this lesson, you should be able to:

  • use techniques for evaluating and decreasing computational time,

  • provide useful information in comments to other programmers,

  • organize your code using proper indenting,

  • choose inputs and outputs wisely,

  • create your own error and warning messages to users.

This lesson is about how to write code that is efficient in the computational power it demands, the time it takes you to write (and especially edit it), and the time it takes for someone else to understand/edit your code.

Just like traditional writing where we use punctuation, paragraphs, lists, fonts, etc. to improve the “visual performance” of our work, the same necessity applies to code. Syntax is the punctuation and grammar. Using appropriate spacing and comments helps the reader categorize and fully understand the code. In MATLAB, using sections helps someone navigate and debug the code.


How can I improve my code for computational efficiency?

Use more efficient functions - Not all functions are created equal. Remember, they are algorithms that perform some function: some set of steps. In some cases, changing the function (algorithm) you use in your code will significantly affect the time it takes to run your program. For example, line() is generally computationally less demanding than plot(). Why not always use the more efficient function?

Write more efficient code - One example of making your code more efficient is to try to reduce the number of loop iterations in it (if applicable). For instance, you might change the structure of your code to get rid of a nested loop or use a binary search. We will not cover this in-depth here, but know that it is important in contexts where computational efficiency is crucial. The salience of computational efficiency is relative, which means you might have a “big” program/large dataset or a “small” computer.

MATLAB Profiler Tool - To help identify specific areas for scrutiny in your program, you can use the MATLAB Profiler tool (see more on their Profile to Improve Performance page). This tool can be run by clicking the “Run and Time” button in the Editor tab next to “Run” (see Figure 1).

Figure 1: The Editor tab highlighting the “Run and Time” button for the MATLAB Profiler.

Figure 2: Output window of the MATLAB Profiler run on Example 2 from Lesson 4.8.

In Figure 2, we see an example output of the MATLAB Profiler. The time to run the whole m-file is given on the first line: 0.344 seconds in this case. We can recognize some of the entries like title(), legend(), close, and polyfit(), while others are not familiar. The unfamiliar lines are functions/commands that execute as a direct result of the code we wrote in our m-file.

Looking at the second line of the Profiler output, we see that the legend() is taking the longest to complete in this program (although still very short). Clicking on the function name in the Profiler will open the Profile Detail Report window (see Figure 3). This will give specific details (down to the line of code) on run time for that function.

You can see in Figure 3 that a summary of the lines that took the longest to run is given as well as the sub-functions or “child” functions. We will end our discussion of the MATLAB Profiler and computational efficiency for now as more programming knowledge and experience are needed to dig deeper into the topic. The principal thing to remember is that there are easy-to-use tools in MATLAB that can help you make your code run faster.

Figure 3: The Profile Detail Report for the legend() function, which was called in an example program.


How does hardcoding impact a program?

If you are new to programming, you have probably never heard of “hardcoding”. It occurs when unnecessary changes inside the body of the code are necessary when the inputs of the program are changed. If a code is written well, only the inputs need to be changed for the program to still be valid (whether that relates to math, syntax, or something else). It is especially problematic if someone else is trying to use your code, but does not know that it only works correctly for specific inputs. For example, you have inputs for the dimensions of a beam but not for the material properties of the beam like Young’s modulus, which you hardcoded later in the program.


What are some tips for good comments and spacing?

It is always important to make proper use of comments in your programs. A few reasons to use good comments are that they:

  • help you understand and write better code,

  • help you debug the code as you are writing the program,

    • Track issues in the code. It can help to use a unique, searchable keyword like “FIX”.

    • Remember why you did “X” a week ago.

    • Provides organization, so you can more easily isolate problems.

  • document the code for future reference (for yourself and others).

Now, a few ways to write good comments are:

  • Organize your code with “stand-out” headings (for longer pieces of code ~100+ lines),

    • Do not overuse these headings as that would defeat the purpose,

    • Put a short, simple description,

  • Leave detailed notes on things that are especially complicated,

  • Leave a comment explaining the purpose of each variable when you define it for the first time.


Why does proper code indenting matter?

You may have noticed that certain blocks of code are indented. There are a number of different cases where this is standard practice, but the two most common are for conditional statements, which you have seen in Module 5, and for loops, which you will see in Module 8. Although MATLAB does not require indenting, some programming languages (like Python) do require proper indenting. In any case, using proper indenting is standard practice in MATLAB because it makes your program more readable and clearer.

Fortunately, MATLAB makes indenting easy with “smart indenting” tools. Just highlight the portion of code you want it to fix and click the appropriate button in the toolbar (see Figure 1).


What are some tips for choosing inputs and outputs?

Choosing appropriate inputs and outputs to your program (and, later in the course, your functions) is a balance between giving the user enough control to make the program useful, but not so many as to overwhelm them. For example, if you are writing a program to calculate the weight of an object (\(\text{w} = \text{mg}\)), obviously weight would be your output. You would want to set the mass of the object as an input but probably not the acceleration due to gravity. However, if you worked at NASA, both the mass and the acceleration due to gravity would be good inputs.

On the other side of things, you do not want to output too much information. For instance, you should avoid outputting too many intermediate steps of the program (as a finished product). If you are writing a program that checks to see whether your item will fit in a certain shipping box, you do not need to report the checks for each of the three dimensions. Just report “fits” or “item too large”.

The key to making good choices is to think about the uses for your code and the audience (users). There are no general rules other than this on making a decision on what you will require from and report to the user.


What are some tips for thinking ahead in when designing my program?

So far in this lesson, we have talked about thinking ahead when writing code in several contexts such as writing informative comments and choosing the appropriate inputs and outputs. However, this is not the extent of planning that should go into your code. As you mature as a programmer, you will start to pick up more things that you will consider as you write a new program. Some common examples of this have to do with numbering conventions. The “Y2K” crisis was caused because no one implemented a simple and “obvious” case for a change in millennia. The problem arose from only a year with its last two digits (e.g., 97, 98, 99, 00).

Not only should we try to anticipate a user’s needs, but we should write programs as robustly as possible whenever possible. That means expecting the unexpected. For example, use the else conditional clause with care as “else” encompasses a lot of things (i.e., everything else). Check user inputs for validity (correct data type, numeric range/sign, etc.).

Multiple Choice Quiz

The content of this page is intentionally blank

Problem Set

The content of this page is intentionally blank