Wednesday, April 9, 2008

Write your source as if it was open

Sometimes you get to read some piece of code and you say "mmm, that's a good piece of code". Well, it doesn't necessarily occur too much, but I hope for you that it does happen, at least occasionally when reading your own code. But in many cases you come to code that makes you shout "who the hell wrote this stuff", and you may recall that it was you as well.

So, what makes a good code?

Is it comments?
Well, comments are important and we will surely dedicate a post to it sometime. But one can think of good code without too many comments. In fact in some cases comments are what makes bad code looks even worse.

Coding guidelines are surely important
Do you really think so? Making your code readable is a must, but as long as you are not doing crazy stuff you can keep your code readable without too much guidelines. Not saying that guidelines are
bad, but this is not what makes good code.

Should it be simple? Should it be sophisticated?
This is in fact a target you cannot really set. The level of simplicity or complexity is an outcome of the problem you are solving. You should not try to get a simple solution for a complex problem, and you should not be too happy with a beautiful monstrosity built for a simple problem having in mind all the other problems that this pretty hide
ous thing may also solve in the future. So simplicity or sophistication per-se is not the target.

Lacking a straightforward answer, let's ask the opposite question...
What makes a bad code?

  • Bad code is a code that you cannot explain
  • Bad code is a code that you find hard to use
  • Bad code is a code that repeats itself
  • Bad code is a code that is tightly coupled - everything needs everything, everyone needs to know anyone else, you cannot go easily from top to bottom, there is no top and no bottom
  • Bad code is a code that you will not feel proud to publish under your name

To avoid writing bad code I suggest that you will think you are writing an open source. Assume someone else, that you do not have direct communication with, is going to use your code, thus your code should have clear API and be modular enough so it can be used in pieces (i.e. one doesn't need to understand the whole thing in order to create the first "Hello World"). And you should write it so you will be proud to publish it. This is writing your code as if it was an open source.


To summarize
  • Pay attention to your API
  • Modularity counts
  • Be proud of your code, if you are not, think why and fix it

No comments: