Take the 2-minute tour ×

I have been coding in MATLAB for like 4 years. However only recently I have experienced writing long codes, or the need for connection of some multiple codes and data. Writing the code in bits as general functions is one of the things I have experienced lately is a good thing to do. I would like to know, as I develop further in writing code in MATLAB and perhaps in Python later, the basic principles and etiquette of writing a good structured code.

1) Please use layman terminologies as I might not be cognizant of all the technical jargon in programming. Like what is the difference between formatting and structuring of a code? - I'm assuming it to be same.

2) I'll appreciate if you can give your own personal experiences, other than the books and sources, while you were starting to program.

share|improve this question

closed as too broad by Josiah Hester, EdChum, Kon, Henry Keiter, sashkello Sep 30 '13 at 0:17


The important thing is that you decompose your problem into simple, manageable parts, and that these parts have as few interdepandancies as possible. Object oriented programming can help with this, as can other methods. I also recommend reading Code Complete, assuming that you will continue to develop larger projects. –  Seamus Aug 30 '10 at 20:20
What do you mean by "few interdepandancies as possible"? Can you elaborate and mention some shortcomings? –  Pupil Aug 30 '10 at 21:13
@Seamus: Functional programming would have been a better example. It takes decomposition to its logical conclusion. –  Clark Gaebel Aug 30 '10 at 22:45
@Harpreet: Sure. Imagine that you have split your problem into smaller parts and started codeing. You reach a point when you need a function that you have already written in one of the other "parts", so you just call the function from the new code. You have created an interdepandancy by doing this because when you go back and change the first "part" to fix a bug or add a feature, you now have to be aware that other code in an arbitrary location depends on it, and you changes have a chance to create a new bug in an arbitrary location in your code. –  Seamus Aug 31 '10 at 16:47
@Harpreet: There are also lots of different styles of programming languages, all of which provide benefits. Object oriented programing is just one programming model, and it is not the answer to all problems. Clark Gaebel mentions functional programming, which is another paradigm that offers solutions to software engineering problems. Unfortunately, functional programing is not available in MATLAB and is an advanced topic in Python. –  Seamus Aug 31 '10 at 16:55

18 Answers 18

up vote 17 down vote accepted

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.
share|improve this answer
I think the first point is good and I have a personal experience with that. To elaborate it further I wrote similar parts in multiple codes where I could have actually called through a function for that part. I did correct it. –  Pupil Aug 30 '10 at 21:42

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.)

share|improve this answer
My copy of Code Complete went missing! All is lost! –  Seamus Aug 30 '10 at 20:21
I wub my copy of Code Complete. What a tragic thing to lose yours! D: –  townsean Aug 30 '10 at 20:22
Ahh -- Steve McConnell. That book is old school but still so relevant! Another good book of his is 'Rapid Development' –  Dan Esparza Aug 30 '10 at 21:12
@Dan Esparza - Oh yes, Rapid Development changed the way I saw how things were being run at work for one of the groups I'm a member of. Since then we've got new managers but the number of classic mistakes...whoo boy! –  wheaties Aug 31 '10 at 1:01
@Dan - the second edition is nice, updated. No need to read if you have the first ed. –  Marc Aug 31 '10 at 12:56

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

share|improve this answer
Thanks for giving the link specifically about Matlab. It will be more useful particularly because as of now I only use Matlab. –  Pupil Aug 30 '10 at 21:47

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.

share|improve this answer
Excellent advice. Either extreme (verbosity or terseness) makes code hard to read. Java and Perl programmers seem to refuse to understand this. –  dsimcha Aug 30 '10 at 21:37
I like that suggestion. It's a very good point, however it must be kept in mind to adhere to it when actually writing a code because its easy listened than followed. –  Pupil Aug 30 '10 at 21:39
I would change that to working readable shortest program :) Working is more important than readable, which is more important than short. +1 though. –  Billy ONeal Aug 31 '10 at 3:06
@Billy ONeal: but then it wouldn't be working English. –  intuited Aug 31 '10 at 6:49
@intuited: Perhaps, but it would be more correct :) –  Billy ONeal Aug 31 '10 at 13:04

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


share|improve this answer
Thanks for the points. Can you give some examples or elaborate the points as I don't understand some of the points like gettors/settors etc. –  Pupil Aug 30 '10 at 21:15
Don't use them - in the vast majority of cases, they're quite redundant. –  Puppy Aug 30 '10 at 21:38
@DeadMG: I hope by that you mean one should implement classes so that getters and setters are unnecessary, rather than that you should expose data members to client code. –  Billy ONeal Aug 31 '10 at 3:07
agree that a lot of people make things redundant by doing stuff like private list whatever, then do a get/set on it. there is an art to designing actually good gettors/settors. –  Luke Belbina Aug 31 '10 at 4:30
@Billy: There's plenty of cases when public member variables make sense. If you write a getter and a setter for a member variable, then you've just done lip service to OO without actually thinking about how it's going to be done. –  Puppy Aug 31 '10 at 8:38

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.

share|improve this answer
The Google style conventions forbid the use of exceptions in C++ and also propose some somewhat contorted rules for passing variables in some circumstances. I wouldn't recommend them that highly. –  Omnifarious Aug 30 '10 at 20:32
+1 for Kernighan and Pike! –  J. Polfer Aug 30 '10 at 22:09

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;
   if i == j 
      return i * j;
     j *= 2;
     if(j == 100)

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.

share|improve this answer
@Harpreet: see edit. –  Paul Nathan Aug 30 '10 at 22:27
@Paul Nathan: You listed "comment your code" twice. Commenting is important, but it's also important not to overdo it. One shouldn't normally have to say 'what' code is doing--that should be obvious from the code; if it isn't obvious, that's often a sign that code should be written more clearly. Comments should focus on 'why' code is doing something, or what assumptions the code is making. A comment like "a += 5; /* Add 4 to a */" doesn't improve readability one iota. –  supercat Aug 30 '10 at 22:29
@supercat: code is not self-commenting. It's far better to overcomment than undercomment. –  Paul Nathan Aug 30 '10 at 22:36
@Harpreet don't comment what code says but what can't say. –  systempuntoout Aug 30 '10 at 22:41
I find the first example a lot clearer. If I see 10 lines of code, I expect it to be doing something pretty complicated. –  intuited Aug 31 '10 at 6:55

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



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


share|improve this answer
But is simplicity the shortest code, or the longest code with no loops or functions? Are templates a simple way to replace functions or an over complicated way? –  Martin Beckett Sep 1 '10 at 1:57

The Python Style Guide is always a good starting point!

share|improve this answer
The Python style guide is more for code formatting, not structure, etc. PEP-20 might be more relevant, aka import this python.org/dev/peps/pep-0020 , but not exactly clear. –  Nick T Aug 30 '10 at 20:14
@Nick T: What is the difference between formatting and structure of a code? I'm sorry but it seems more or less same to me. –  Pupil Aug 30 '10 at 21:17
Structure - how you organize the code on a large scale, in other words, what functions/objects/logic get placed where. Formatting - this is usually used to describe details on coding that don't necessarily affect its interpretation by the compiler - where to place a newline, where to put comments, how to use tabs+newlines to present a statement in a clear way. –  J. Polfer Aug 30 '10 at 22:09

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.

share|improve this answer

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.

share|improve this answer
Can you give the link to the SICP from MIT you are referring to? –  Pupil Aug 30 '10 at 21:50
mitpress.mit.edu/sicp –  Josh Infiesto Aug 30 '10 at 22:10

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.

share|improve this answer
Good points, specially the consistency in coding. –  Pupil Aug 30 '10 at 22:30

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)


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

share|improve this answer

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
share|improve this answer
A URL would work wonders for the answer. –  Jonathan Leffler Sep 1 '10 at 1:05
Is there a link to see the points that you have mentioned in examples? –  Pupil Sep 2 '10 at 19:47

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

Never code while drunk.
share|improve this answer
can't say that I've tried that one >.> –  townsean Aug 30 '10 at 20:21
Weirdly enough, a little alcohol can make me a much more effective coder, but I would never try to do any significant design work in that state. –  Omnifarious Aug 30 '10 at 20:33
Someone will link, may as well be me: xkcd.com/323 –  Liran Orevi Aug 30 '10 at 21:14
@Liran: First thing I thought of when I read this answer. :D –  Doresoom Aug 31 '10 at 14:22

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

share|improve this answer

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.

share|improve this answer
Thanks for the answer. However I could not, frankly, understand what is meant by these things. It'll be good if you can show them through some example with a code. –  Pupil Sep 2 '10 at 19:42
@Harpreet: I'd like to provide code examples but this might be beyond the scope of this platform. You will find code examples for xUnit in the downloadable zip file at Matlab Central. A good, non free, resource for bug tracking is atlassian.com/software/jira. –  zellus Sep 2 '10 at 23:22

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.

share|improve this answer

protected by bla Jul 18 '13 at 15:41


Would you like to answer one of these unanswered questions instead?
