Thursday, February 7, 2008

Favor 'Read' Time over 'Write' Time

There are thousands of books and millions of web pages that will define modularity and explain you how to achieve them in your program. I am not going to talk about that here. I will answer you why modularity is important.

Any program can be written in just one single method (or function). At least theoretically? The people who are new to programming do this till they are told about "Abstraction", "Encapsulation", etc. Still I see many programmers not following this. They don't modularize their program well. Sure, they understand what is going on but it's not about them. Code should be written keeping in mind that it will be read many times by many people.

557774423456789.

Can you repeat the number? Don't peak! :-)

(Most of us would have not even read it completely just looking at those many digits)

Now, read this: 55-777-44-23456789.

So, which one was easier to read? And which one was easier to write? The first form (without the hyphen separator) was easier to write if you have this number memorized but it is hard to read and recollect for someone who is not familiar with this number. At the same time, the second form took some more time to carefully break at the right places and make it easy for the reader. We invested some more time in writing to save a lot of time for others to memorize this.

This is the whole point. When you write code, you surely understand and it may seem trivial and waste of time to do "separation of concerns." But it's not about you or me, its about that someone who is going to maintain your code in future long after you have moved to another project. Make sure that she won't curse you :-)

Sunday, February 3, 2008

Programming Language of 2007

And the award goes to... Python!?!

Source: http://www.tiobe.com/tpci.htm


I must tell this very frankly, I am pleasantly surprised for one reason: The programming language I learned in 2007 is Python. And now it is declared as the programming language of the year. I am feeling lucky :)

When I started learning it, I hated it for one reason ---Dynamic Typing. Coming from a heavy Java background this was a hard unlearning curve for me. I debated a lot on this topic with my friends and coworkers. I debated on Python forums about this. A very strong debate that I had can be found here (you will have fun reading this, I had fun reading my own post after a very long time!): How to program safely in Python?

Not only this, Guido van Rossum once replied in my post in one of the mailing lists when I asked about Why isn't there a try-catch-finally block in Python? It's available only from Python 2.5+. After pondering, I came to the conclusion that every programming language has its own pros and cons and Python is one such beautiful and stylish language. Yes, you don't have a compiler, yes you will have a python-bite at runtime, but guess what? A compiler only tells that your program is syntactically right. The best way to ensure that your program works is by testing, testing and more testing. Like Bruce Eckel once said, "If it isn't tested, it's broken."

Tuesday, November 13, 2007

Introduction to Algorithms (An OpenCourseWare from MIT)

One of my friends (Manu Garg) told me about this course by MIT on Algorithms. Here are the links if you are interested:

Course Home | Course Download page | Video & Audio lectures of the course

I found a way to download these courses and also some other lectures of the prerequisites for this course by Googling. Yes, it's legal and it's from MIT's website.
One of the prerequisites for this course is "6.001 Structure and Interpretation of Computer Programs." The first version of this course's video lectures are available here for download.

Downloading 6.046J / 18.410J Introduction to Algorithms:

The URLs of the video lectures for Introduction to Algorithms have the following format:
http://mfile.akamai.com/7870/rm/mitstorage.download.akamai.com/7870/6/6.046j/f05/lecturenotes/ocw-6.046-07sep2005-220k.rm
If you'd like to download the entire file and play it, use the following URL:
http://ocw.mit.edu/ans7870/6/6.046j/f05/lecturenotes/ocw-6.046-07sep2005-220k.rm
The only change is the part in bold and red (i.e., till mitstorage.download.akamai.com/ in the first URL, the rest is the same.)

Extra, extra:

More Extra:

Steve Skiena's, the author of the infamous Algorithm Design Manual, lectures are available for viewing from here. He also has videos of his discrete mathematics lectures here.

Monday, August 27, 2007

Java :: FindBugs :: Dead Store

I ran FindBugs on one of our projects and I had a warning on some code similar to this, let's see how the code was written. This is just a sample code to show an example, don't expect any logic here :-)

// DeadStoreExample.java
import java.util.ArrayList;
import java.util.List;

public class DeadStoreExample {
public static void main(String[] args) {
List list = new ArrayList(); // Dead Store here.
list = getList();
System.out.println(list);
}

private static List getList() {
// Some intense operation and finally we return a java.util.List
return new ArrayList();
}
}

FindBugs reported me this problem: Dead store to list in DeadStoreExample.main(String[]). When I first saw it, I was like "What do you mean by Dead Store?" And when I looked into the code I saw a List object being created but not used. Instead, in the next line the reference variable is pointing to some other object in the heap. The object created on line number 6 is never used and hence it's a dead store.

So, what is a Dead Store? If we assign a value to a local variable, but the value is not read by any subsequent instruction, then it's called a Dead Store.

I love FindBugs, the thing that I like the most about FindBugs is that it tries to find all the lame bugs which many veteran programmers accidentally make. I always like to set my compiler warnings very high (even for my Javadoc comments). And now I have developed a habit of running FindBugs before I make a build or commit my code. It's one of those things like Unit Testing, you must try and get infected.

If a compiler or a tool can catch a bug, then I will always go for it. No one can write bug free code, at least I have not seen anyone till now. And I believe in automating anything that is possible so that we never have to do that manually again. That's why we have computers :-)

If you're not using FindBugs, I highly recommend that you to use it.

Sunday, August 26, 2007

Python :: Calculate the Size of a MySQL Schema Approximately

Hi,

Recently I wanted to find out the total size of a schema in a MySQL database. I searched for it but can't really find it. So, I wrote something on my own, really simple which doesn't really bother about a lot of error conditions. But I think that's ok, I mean really this is not a project. I am posting my code here now, feel free to optimize it and tweak it to your own requirement and let me know if you have a better solution :-)

#!/usr/bin/python

"""Calculates the total size of a MySQL database schema approximately."""

import MySQLdb
import getpass

def main():
    db_host = raw_input('Host name: ')
    schema_name = raw_input('Schema name: ')
    user_name = raw_input('User name: ')
    password = getpass.getpass('DB Password: ')
    db_conn = MySQLdb.connect(host=db_host, user=user_name,
            passwd=password, db=schema_name)
    db_cursor = db_conn.cursor(MySQLdb.cursors.DictCursor)
    db_cursor.execute('show table status')
    rows = db_cursor.fetchall()
    total_size = 0
    for row in rows:
        data_length = row['Data_length']
        if data_length is None:
            data_length = 0
        index_length = row['Index_length']
        if index_length is None:
            index_length = 0
        total_size = total_size + data_length + index_length
    print '------------------------'
    print 'Total size: %s KB.' % str(total_size / 1024)
    db_conn.close()


if __name__ == '__main__':
    main()

I didn't add any exception handling code, I thought it would clutter the actual code I wanted to show.

Friday, April 27, 2007

Eclipse :: Configuring Eclipse Startup

If your eclipse is starting up a little slower or if it's running a little slower or if it gets an OutOfMemoryError, then just go through this checklist:-

  • Is it using the latest and the fastest JRE?

  • Is it having a good minimum and maximum memory?


And then follow this lovely blog:-
http://swem.wm.edu/blogs/waynegraham/index.cfm/2006/9/7/Tweaking-Eclipse

Let me know if the link doesn't work :-)

Monday, April 2, 2007

Java :: Constants Interface or Constants Class?

We all know about patterns and anti-patterns. One anti-pattern that has been hated by many people is the Constant Interface anti-pattern. Java doesn't support globals directly, but sometimes you will need to have a few things as global. Meaning, accessible to every class in your entire program.

In Java to get the platform independent new line character, we write the following code:

final String NEW_LINE = System.getProperty("line.separator");

But the new line character is something any class in our program may need and writing System.getProperty("line.separator") is not good for two reasons.
  1. We may misspell the key 'line.separator' in which case we'll get a 'null' back, and
  2. It's inefficient.
A better way is to get this new line character one time, store it in the memory and make it accessible to all the classes in our program. This kind of a situation led to the invention of the "Constant Interface" anti-pattern. People implemented this pattern like this:

public interface Constants {
String NEW_LINE = System.getProperty("line.separator");
}

And the client of this 'Constants' interface started implementing this interface for convenience reasons. This is a bad idea because let's say this 'Constants' interface has 100 constants and a client class implements this interface for convenience reasons, all the 100 constants from the interface end up being a part of the public API of the client class. This breaks inheritance and you can by now imagine how the Javadoc will look like for this client class.

OK, we may ask all of our clients of this 'Constants' interface that they must not implement this interface and they should only see it as a place where global constants are stored, but what's the guarantee that they will NOT implement this interface?

Thankfully we have a better way of doing this, see the following code:

public class Constants {
public static final String NEW_LINE = System.getProperty("line.separator");

private Constants() {
// Private constructor to enforce un-instantiability.
}
}

The above 'Constants' class has the following benefits over the 'Constants' interface:
  1. No client can instantiate, because the constructor is private
  2. No client can extend, again for the same reason, the constructor is private
Having a class for constants and making it's constructor private is a much better approach than using an interface.