45

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

  • 12
    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 Connor Aug 30 '10 at 20:20
  • 2
    @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 Connor Aug 31 '10 at 16:47
  • @Harpreet: Of course, completely avoiding interdepandancies is impossible, so you need to manage them in a logical way. In object oriented programming, you are provided with tools to do just that. Classes and interfaces are two very important concepts. A class allows you to group functionality (methods) and state (member variables) into a logical module. Once you do that, you can "outline" the interdepandancies using an interface, which is basically a contract stating what a class does. – Seamus Connor Aug 31 '10 at 16:52
  • 1
    @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 Connor Aug 31 '10 at 16:55
  • An easy-to-read article on the subject: [Best Practices for Scientific Computing](http://dx.doi.org/10.1371/journal.pbio.1001745) (via [Loren Shure's MathWorks blog](http://blogs.mathworks.com/loren/2014/01/29/coding-best-practices-a-good-read/)). – horchler Feb 01 '14 at 00:58

18 Answers18

34

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

wheaties
  • 35,646
  • 15
  • 94
  • 131
22

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.
anthony
  • 40,424
  • 5
  • 55
  • 128
17

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

Matthew Simoneau
  • 6,199
  • 6
  • 35
  • 46
15

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.

  • 1
    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. –  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 03:06
  • @Billy ONeal: but then it wouldn't be working English. – intuited Aug 31 '10 at 06:49
  • @intuited: Perhaps, but it would be more correct :) – Billy ONeal Aug 31 '10 at 13:04
7

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

Luke Belbina
  • 5,708
  • 12
  • 52
  • 75
  • 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 03: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 04: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 08:38
  • @DeadMG: Until next week you decide to calculate the value instead of using a variable, and all of your clients need to be modified and recompiled. (Though I agree in general that every variable should not have a getter/setter, if it's in a situation where it has to act like a public variable, it should have getters and setters instead of exposing the field. – Billy ONeal Aug 31 '10 at 13:02
5

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.

aoeu
  • 1,128
  • 2
  • 13
  • 22
  • 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
5

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.

Paul Nathan
  • 39,638
  • 28
  • 112
  • 212
  • @Harpreet: Some people like to have very condensed code- the fewest lines of code in a file, do more with less code. That eventually makes it hard for read for someone who is unfamiliar with the programming language and the program. – Paul Nathan Aug 30 '10 at 22:01
  • 5
    @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
  • 2
    @supercat: code is not self-commenting. It's far better to overcomment than undercomment. – Paul Nathan Aug 30 '10 at 22:36
  • @Paul: Yes, I think that is the best option - to include 1) what the code is doing, and 2) why and assumptions of the algos...getting over comment is not a problem if the code looks clean and not messy making it hard to understand on a glance. –  Aug 30 '10 at 22:40
  • 2
    @Harpreet don't comment what code says but what can't say. – systempuntoout Aug 30 '10 at 22:41
  • 1
    @supercat: the biggest problem with your sample comment is that it's wrong; a+=5 does not add 4... even for very large values of 4. – Mikeage Aug 31 '10 at 04:03
  • 5
    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 06:55
3

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.

systempuntoout
  • 71,966
  • 47
  • 171
  • 241
  • 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 01 '10 at 01:57
2

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.

Community
  • 1
  • 1
bla
  • 25,846
  • 10
  • 70
  • 101
2

The Python Style Guide is always a good starting point!

jathanism
  • 33,067
  • 9
  • 68
  • 86
  • 1
    The Python style guide is more for code formatting, not structure, etc. PEP-20 might be more relevant, aka `import this` http://www.python.org/dev/peps/pep-0020/ , but not exactly clear. – Nick T Aug 30 '10 at 20:14
  • 2
    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
2

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.

Community
  • 1
  • 1
Rook
  • 60,248
  • 49
  • 165
  • 242
2

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.

afkbowflexin
  • 4,029
  • 2
  • 37
  • 61
2

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.

Kennzo
  • 437
  • 2
  • 11
2

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

cpf
  • 1,461
  • 2
  • 15
  • 26
2

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
xiao 啸
  • 6,350
  • 9
  • 40
  • 51
2

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.

zellus
  • 9,617
  • 5
  • 39
  • 56
  • @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 http://www.atlassian.com/software/jira/. – zellus Sep 02 '10 at 23:22
1

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

Never code while drunk.
Ryan Gooler
  • 2,025
  • 1
  • 13
  • 14
1

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

Humphrey Bogart
  • 7,423
  • 14
  • 52
  • 59