Good practices in writing MATLAB code?

I would like to know the basic principles and etiquette of writing a well structured code.

Answers


These are the most important two things to keep in mind when you are writing code:

  1. Don't write code that you've already written.
  2. Don't write code that you don't need to write.

Read Code Complete, it will do wonders for everything. It'll show you where, how, and when things matter. It's pretty much the Bible of software development (IMHO.)


MATLAB Programming Style Guidelines by Richard Johnson is a good resource.


Well, if you want it in layman's terms:

I reccomend people to write the shortest readable program that works.

There are a lot more rules about how to format code, name variables, design classes, separate responsibilities. But you should not forget that all of those rules are only there to make sure that your code is easy to check for errors, and to ensure it is maintainable by someone else than the original author. If keep the above reccomendation in mind, your progam will be just that.


This list could go on for a long time but some major things are:

  • Indent.
  • Descriptive variable names.
  • Descriptive class / function names.
  • Don't duplicate code. If it needs duplication put in a class / function.
  • Use gettors / settors.
  • Only expose what's necessary in your objects.
  • Single dependency principle.
  • Learn how to write good comments, not lots of comments.
  • Take pride in your code!

Two good places to start:

Clean-Code Handbook

Code-Complete


If you want something to use as a reference or etiquette, I often follow the official Google style conventions for whatever language I'm working in, such as for C++ or for Python.

The Practice of Programming by Rob Pike and Brian W. Kernighan also has a section on style that I found helpful.


First of all, "codes" is not the right word to use. A code is a representation of another thing, usually numeric. The correct words are "source code", and the plural of source code is source code.

--

Writing good source code:

  1. Comment your code.
  2. Use variable names longer than several letters. Between 5 and 20 is a good rule of thumb.
  3. Shorter lines of code is not better - use whitespace.
  4. Being "clever" with your code is a good way to confuse yourself or another person later on.
  5. Decompose the problem into its components and use hierarchical design to assemble the solution.
  6. Remember that you will need to change your program later on.
  7. Comment your code.

There are many fads in computer programming. Their proponents consider those who are not following the fad unenlightened and not very with-it. The current major fads seem to be "Test Driven Development" and "Agile". The fad in the 1990s was 'Object Oriented Programming'. Learn the useful core parts of the ideas that come around, but don't be dogmatic and remember that the best program is one that is getting the job done that it needs to do.

very trivial example of over-condensed code off the top of my head

for(int i=0,j=i; i<10 && j!=100;i++){
     if i==j return i*j; 
     else j*=2;
}}

while this is more readable:

int j = 0;
for(int i = 0; i < 10; i++)
{
   if i == j 
   {
      return i * j;
   }
   else
   { 
     j *= 2;
     if(j == 100)
     {
        break;
     }
   }
}

The second example has the logic for exiting the loop clearly visible; the first example has the logic entangled with the control flow. Note that these two programs do exactly the same thing. My programming style takes up a lot of lines of code, but I have never once encountered a complaint about it being hard to understand stylistically, while I find the more condensed approaches frustrating.

An experienced programmer can and will read both - the above may make them pause for a moment and consider what is happening. Forcing the reader to sit down and stare at the code is not a good idea. Code needs to be obvious. Each problem has an intrinsic complexity to expressing its solution. Code should not be more complex than the solution complexity, if at all possible.

That is the essence of what the other poster tried to convey - don't make the program longer than need be. Longer has two meanings: more lines of code (ie, putting braces on their own line), and more complex. Making a program more complex than need be is not good. Making it more readable is good.


Have a look to 97 Things Every Programmer Should Know. It's free and contains a lot of gems like this one:

There is one quote that I think is particularly good for all software developers to know and keep close to their hearts:

Beauty of style and harmony and grace and good rhythm depends on simplicity. — Plato

In one sentence I think this sums up the values that we as software developers should aspire to.

There are a number of things we strive for in our code:

  • Readability
  • Maintainability
  • Speed of development
  • The elusive quality of beauty

Plato is telling us that the enabling factor for all of these qualities is simplicity.


The Python Style Guide is always a good starting point!


European Standards For Writing and Documenting Exchangeable Fortran 90 Code have been in my bookmarks, like forever. Also, there was a thread in here, since you are interested in MATLAB, on organising MATLAB code.


Personally, I've found that I learned more about programming style from working through SICP which is the MIT Intro to Comp SCI text (I'm about a quarter of the way through.) Than any other book. That being said, If you're going to be working in Python, the Google style guide is an excellent place to start.

I read somewhere that most programs (scripts anyways) should never be more than a couple of lines long. All the requisite functionality should be abstracted into functions or classes. I tend to agree.


Many good points have been made above. I definitely second all of the above. I would also like to add that spelling and consistency in coding be something you practice (and also in real life).

I've worked with some offshore teams and though their English is pretty good, their spelling errors caused a lot of confusion. So for instance, if you need to look for some function (e.g., getFeedsFromDatabase) and they spell database wrong or something else, that can be a big or small headache, depending on how many dependencies you have on that particular function. The fact that it gets repeated over and over within the code will first off, drive you nuts, and second, make it difficult to parse.

Also, keep up with consistency in terms of naming variables and functions. There are many protocols to go by but as long as you're consistent in what you do, others you work with will be able to better read your code and be thankful for it.


Pretty much everything said here, and something more. In my opinion the best site concerning what you're looking for (especially the zen of python parts are fun and true)

http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html

Talks about both PEP-20 and PEP-8, some easter eggs (fun stuff), etc...


You can have a look at the Stanford online course: Programming Methodology CS106A. The instructor has given several really good instruction for writing source code.

Some of them are as following:

  1. write programs for people to read, not just for computers to read. Both of them need to be able to read it, but it's far more important that a person reads it and understands it, and that the computer still executes it correctly. But that's the first major software engineering principle to think about.

  2. How to make comments:  put in comments to clarify things in the program, which are not obvious

  3. How to make decomposition

    1. One method solves one problem
    2. Each method has code approximate 1~15lines
    3. Give methods good names
    4. Write comment for code

Unit Tests Python and matlab are dynamic languages. As your code base grows, you will be forced to refactor your code. In contrast to statically typed languages, the compiler will not detect 'broken' parts in your project. Using unit test frameworks like xUnit not only compensate missing compiler checks, they allow refactoring with continuous verification for all parts of your project.

Source Control Track your source code with a version control system like svn, git or any other derivative. You'll be able to back and forth in your code history, making branches or creating tags for deployed/released versions.

Bug Tracking Use a bug tracking system, if possible connected with your source control system, in order to stay on top of your issues. You may not be able, or forced, to fix issues right away.

Reduce Entropy While integrating new features in your existing code base, you will add more lines of code, and potentially more complexity. This will increase entropy. Try to keep your design clean, by introducing an interface, or inheritance hierarchy in order to reduce entropy again. Not paying attention to code entropy will render your code unmaintainable over time.

All of The Above Mentioned Pure coding related topics, like using a style guide, not duplicating code, ..., has already been mentioned.


A small addition to the wonderful answers already here regarding Matlab:

  • Avoid long scripts, instead write functions (sub routines) in separate files. This will make the code more readable and easier to optimize.

  • Use Matlab's built-in functions capabilities. That is, learn about the many many functions that Matlab offers instead of reinventing the wheel.

  • Use code sectioning, and whatever the other code structure the newest Matlab version offers.

  • Learn how to benchmark your code using timeit and profile . You'll discover that sometimes for loops are the better solution.


The best advice I got when I asked this question was as follows:

Never code while drunk.

Make it readable, make it intuitive, make it understandable, and make it commented.


Need Your Help

How to find two most distant points?

algorithm language-agnostic geometry

This is a question that I was asked on a job interview some time ago. And I still can't figure out sensible answer.

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

android android-edittext

I have read Android: Limiting EditText to numbers and How do I show the number keyboard on an EditText in android?. Unfortunately, none of them seems to fit my needs.