Many of the beginner (well, and not beginner) developers as well are sometimes wondering - what is more important - readable code or comments? Now, I would like to warn you - the opinion expressed in this blog post is my own, therefore it might or might not be the same as yours.
I do think that readable code that can be esily understood and the logic analyzed without much reading is an asset for any application. Especially, this applies to large chunks of code. For example, let's take a look at this code:
CODE
// Initialize a SQL connection that is null
SqlConnection c = null;
// Create the actual SQL connection
c = new SqlConnection("Data Source=server;Initial Catalog=init;User Id=admin;Password=asdfh4CHsjO3;");
// Open SQL connection.
c.Open();
// Build the SQL query
string sc = string.Format("SELECT [F1] FROM [F2].[CAT].[SMTHNGELSE] WHERE CN='{0}'", TextBox1.Text);
// Create a new SQL command
SqlCommand c2 = new SqlCommand(sc, c);
This is some generic C# code designed to connect to a database. As you see, the imaginary developer who wrote this code used a lot of comments. But, most of them are absolutely useless. For example, why would anyone need to tell the person who is reading the code that
SqlConnection c = null; will
// Initialize a SQL connection that is null. This comment, however, is cluttering the overall code. Also, the variable names are a bit meaningless, considering the fact the code is going to be reused over and over again.
Now, imagine the situation where there are no comments in the code and you see this:
CODE
c.Open();
What exactly is being opened? Nobody knows and chances are that even the initial developer will forget what is the purpose of that mystical
c in the algorithm.
Now, let's take a look at another piece of code (actually, it is the same as above, only modified a bit):
CODE
SqlConnection sqlConnection = null;
sqlConnection = new SqlConnection("Data Source=server;Initial Catalog=init;User Id=admin;Password=asdfh4CHsjO3;");
sqlConnection.Open();
string sqlQuery = string.Format("SELECT [F1] FROM [F2].[CAT].[SMTHNGELSE] WHERE CN='{0}'", TextBox1.Text);
SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
As you see - no comments used at all, but you can still see the and understand the overall code logic, because the variables have very descriptive names, and now, if you see
sqlConnection.Open();, you are quite positive that a SQL connection is being opened.
Of course, I don't say that comments are not needed. It would be great to introduce this in before the actual code:
CODE
// A method that connects to the database
// that contains the users that are allowed to
// access the backend of the system
But comments should, in my opninion, be reduced to the minimum and replaced with extremely readable code. This is not hard, once you start paying more attention to the variable/method/function etc. naming conventions that will allow you to dive into the code without reading additional pages of comments.