views:

1126

answers:

17

I am an engineering student, not computer science though, and 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.

P.S: Guys thank you for your answers:

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.

+20  A: 

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
My copy of Code Complete went missing! All is lost!
Seamus
I wub my copy of Code Complete. What a tragic thing to lose yours! D:
townsean
Ahh -- Steve McConnell. That book is old school but still so relevant! Another good book of his is 'Rapid Development'
Dan Esparza
@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
@Dan - the second edition is nice, updated. No need to read if you have the first ed.
Marc
@Marc - I prefer the first edition, the second one seems to concentrate on BDUF as the solution to everything
Martin Beckett
+1  A: 

The Python Style Guide is always a good starting point!

jathanism
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
@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.
Harpreet
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.
sheepsimulator
+4  A: 

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

nextgenneo
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.
Harpreet
Don't use them - in the vast majority of cases, they're quite redundant.
DeadMG
@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
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.
nextgenneo
@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.
DeadMG
@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
A: 

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

Never code while drunk.
Ryan Gooler
can't say that I've tried that one >.>
townsean
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
Someone will link, may as well be me: http://xkcd.com/323/
Liran Orevi
@Liran: First thing I thought of when I read this answer. :D
Doresoom
+2  A: 

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.

noneme
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
+1 for Kernighan and Pike!
sheepsimulator
+1  A: 

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.

Rook
Thanks for giving the link specifically about Matlab. It will be more useful particularly because as of now I only use Matlab.
Harpreet
+9  A: 

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.

jdv
Excellent advice. Either extreme (verbosity or terseness) makes code hard to read. Java and Perl programmers seem to refuse to understand this.
dsimcha
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.
Harpreet
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
@Billy ONeal: but then it wouldn't be working English.
intuited
@intuited: Perhaps, but it would be more correct :)
Billy ONeal
+5  A: 

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
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.
Harpreet
+1  A: 

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.

Josh
Can you give the link to the SICP from MIT you are referring to?
Harpreet
http://mitpress.mit.edu/sicp/
Josh
+6  A: 

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

Matthew Simoneau
Thanks for giving the link specifically about Matlab. It will be more useful particularly because as of now I only use Matlab.
Harpreet
+3  A: 

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
"Shorter lines of code is not better - use whitespace". What does this mean?
Harpreet
@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
So you mean those shorter condensed codes should be avoided? It is contradicting with the suggestion given by one which says: "shortest readable program that works"
Harpreet
@Harpreet: see edit.
Paul Nathan
@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
@supercat: code is not self-commenting. It's far better to overcomment than undercomment.
Paul Nathan
@supercat: I think you mentioned a very good point. Till now I had been putting in comments about what you suggested to avoid - that is what the code is doing.
Harpreet
@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.
Harpreet
@Harpreet don't comment what code says but what can't say.
systempuntoout
@systempuntoout: Point taken.
Harpreet
@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
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
+1  A: 

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
Good points, specially the consistency in coding.
Harpreet
+1  A: 

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
+2  A: 

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
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
+1  A: 

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
A URL would work wonders for the answer.
Jonathan Leffler
@xiao: Is there a link to see the points that you have mentioned in examples?
Harpreet
A: 

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

Beau Martínez
A: 

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