Monday, May 21, 2007

Some Comments About Commenting

Lately I have seen far too much undocumented code. It seems that no one really appreciates the power of good commenting anymore.

I'm a pretty good coder, I think, and so are many of the people I work with. But for some odd reason, I don't remember anyone taking comments as seriously as I do.

Commenting is what makes the difference!
Comments are the difference between good code and excellent code, and as such, they make the difference between a good coder and an excellent coder.

Nobody like to comment their code, and I really don't know why, but I suspect a part of the problem is not knowing how to comment code in a good manner, or not recognizing good comments when you see them.

So I've decided to compile a short list of tips for the common coder, who now have to sit and write some comments for the first time in his life.
Here they are, from least important to most important:

9 Tips for Good Commenting


9. Don't write too long, but don't write too short

Writing "War and Peace" in your code will not do anyone good, everybody knows that.
But more often, you will find out comments that are simply not helpfull, all in the name of shorthand writing.

Writing "sets X according to the database value" is far better than "this line of code sets X according to the value that was returned from the database", no doubt about it. However, how many times did you see a comment that said "sets X" and that's it? Writing those extra 5 words won't cost you more than a few seconds, and can save a lot of time to whoever it may be that will read your code in the future.
It might even be you...

8. Not all comments must be operational

Not all your comments need to describe exactly what happens in the next line.
Comments like "don't forget to set variable X", "to activate these settings you must call function F" or "this code affects function F2" can sometimes be more helpful.

Keep in mind that sometimes code segments are copy-pasted - not a best practice, but it happens a lot - and it could help to know which other places the copied code segment affects.

7. Don't leave dead code in comments

If you don't need it, delete it. I know it's hard, but just let it go...

If you have some brilliant piece of code you just have to keep for the next generations, just in case they will need to do something like that in some other place - you can put it on external documentation, write an email, or post it in your favorite forum. If it's not used, don't keep it in the code!

If you suspect a line of code will be necessary in the very near future, you can leave it, but explain what it does. Write a comment before the dead code that makes it crystal clear why you left it there.

6. Beware of copy-pasted comments

Come on, guys, this is the oldest trick in the book. We've all suffered from copy-pasted code gone bad. However, copy-pasted code gone bad usually get fixed quickly, since it's bound to be discovered sooner or later. Copy-pasted comments, on the other hand, just stay in the code and get rotten.

You copy a block of code, with comments, and you just change the variables you need in the code, and you end up with a comment that has nothing to do with the code. The next time anyone will look at this code he wouldn't understand where the comment came from, so he might leave it as it is "just in case"...

5. Use correct language

This is a problem especially with non-native English speakers, that must write their comments in English (such as myself).
I don't expect the comments to demonstrate impeccable writing skills in a foreign language, but every one that has basic understanding of the language can tell the difference between "returns the X object if it exists" and "object X to return or null".

Even if the comment can be understood without using proper English, it will take an extra second or two to understand it. It could also cause mistakes simply because the person who read the comment didn't understand it correctly. Not a life or death matter, but it is still very important.

4. Don't be afraid of repeating yourself

Don't be afraid of repeating yourself. Over and over again, when necessary. The same sentence can appear in 4 different procedures, and maybe a couple of times in the same procedure. Remember, probably nobody will ever read your code like a storybook, as a whole. The reader will not mind that some comments repeat themselves. Sometimes the reader will only look at one part of your code, at one specific function.

It's OK to write the meaning of a variable or parameter in the constructor, setter, and every function that use it. It's more than OK, it's better to do so than to write the meaning of the variable only once in some private function that is only used way down the call stack. This way the programmer will not need to drill down only to discover the meaning of a parameter he is using.

So again, when commenting, don't be afraid of repeating yourself.

3. Don't be afraid to comment the obvious

The important point here again is that nobody will read your code like a book. Nobody will be upset if you write a comment stating the obvious. The fact is for most programmers, even the most experienced, it is easier to read natural language than code. That's just the way the human mind works.

Try to read this simple code and you will understand:

private int multi(int a, int b)
{
return a*b;
}


You could guess from the name that this function multiplies two numbers.
However, you could not be sure until you read the whole function.
If you read the following example instead:

// This function multiplies two numbers
private int multi(int a, int b)
{
return a*b;
}


You only have to read the first line to understand it.
If you have a comment for every couple of rows in your code, you don't have to delve into the code every time to understand it, you can find the part you need quickly.

This example may seem a little silly, but this is the same for 5 rows long functions or 50 rows long functions, and hopefully you don't have functions much longer than that in your code :)

2. Comment the why, not only the how

OK, now we are getting serious. Whenever we comment a piece of code, we should not only comment what we are doing and how, we should also comment why we are doing what we are doing.

I have a couple of way to comment this method:
public MyClass(int myProp1, int myProp2, string myProp3)
{
this._myProp1 = myProp1;
this._myProp2 = myProp2;
this._myProp3 = myProp3;
}


I could comment the how:
// This is the constructor for class MyClass
public MyClass(int myProp1, int myProp2, string myProp3)
{
// initialize private properties
this._myProp1 = myProp1;
this._myProp2 = myProp2;
this._myProp3 = myProp3;
}


But I better comment the why:
// This is the constructor for class MyClass.
// This class does this and that.
// Classes that creates MyClass should do X, Y and Z.
public MyClass(int myProp1, int myProp2, string myProp3)
{
// initialize private properties:
// _myProp1 controls this behavior
this._myProp1 = myProp1;
// _myProp2 controls that behavior
this._myProp2 = myProp2;
// _myProp3 is displayed on screen when X happens.
// It can be omitted, and then the default message
// is displayed.
this._myProp3 = myProp3;
}


Isn't that a lot better? When reading this code, I know why I need to initialize myProp1 in the constructor, and what is the purpose of doing so.

Commenting the why is the key for good commenting. If you take only one thing from this post, take this.
Programmers are not idiots. They can read code - and if they can't, it won't help no matter how much comments you give them. But a line of code cannot express the meaning or spirit of the whole program. This is why you should comment, to explain the place of this specific line of code in the overall stucture of your system.

And now, for the number one tip of good commenting...

1. Comment

...As opposed to "do not comment", of course.

You know what they say, practice makes perfect - so start commenting today!

Make it a habit to comment your code when you are writing it, not afterwards. It always helps to think a little before you code. So while you're at it, planning how your code will work and all the bits and bytes, you already know why you need to write this piece of code. You know it now, but tomorrow you may forget. Someone else that will look at the code will not know. So tell him why you wrote it, and what it is supposed to do.

Believe me, before you know it you will not be able to code without commenting.


I hope this helps, and if a single helpful comment was born as a result of my post, my work here is done :)

Labels: ,

Saturday, January 20, 2007

מפנה מקום באייפוד לשירים שלך

אם ברי סחרוף היה כותב היום את השיר "מפנה מקום", מעניין אם הוא היה נשמע כך:

אני מפנה מקום בנייד למספרים שלך
מפנה מקום בדיסק למסמכים שלך
מפנה מקום באייפוד לשירים שלך
מפנה מקום במסך בשביל הרקע שלך
אני מפנה מקום באימייל למכתבים שלך
מפנה מקום במסנג'ר לחברים שלך
מפנה מקום בבלוג לתגובות שלך

כל כך הרבה מקום, ואת בשלך... את בשלך

כל כך הרבה מקום
את יכולה לעשות לוג-און
ואם תהיי לגמרי שלי
אני אצטרך לקנות עוד דיסק-און-קי


וובכן, מזל שהשיר הוקלט בשנת 1995 ולא 2005.

Labels:

Wednesday, November 15, 2006

פח הזבל של האנושות

הפסקתי לקרוא בלוגים.
ניתקתי את האינטרנט.
כיביתי את המחשב.

יום אחד קמתי בבוקר ואמרתי "די!".
די לפשפש בערימות הזבל, לזפזפ בין גרפומנים מקושקשים לאנשי דעת רהוטים, לקרוא עוד ועוד בלוגי מציאות, בלוגי כלכלה, בלוגי טכנולוגיה, בלוגי אמנות ובלוגי מדע וטבע.
שוב ושוב אתה מוצא את עצמך בוהה במסך המרצד בשעות הקטנות של הלילה, תוהה לאן נעלמו להן שוב 3 או 4 שעות מחייך, וממלמל לעצמך בלחש "רק עוד אתר אחד קטן... רק עוד אחד".
ההומור כבר אינו מצחיק, החדשות דרמטיות מדי, הריאליטי נדוש מדי, והדברים אותם אתה "לומד" בשיטוטים האינסופיים נעלמים מראשך באותה המהירות שבה מתעדכנים האתרים, כלומר מדי יום ביומו.

והפרסומות, אלוהים, הפרסומות!
קופצות עליך בין כל קליק לקליק, אורבות לך בנבכי האתרים, מפמפמות לך במוח באופן בלתי פוסק, ואתה, כארנב שנלכד באורם של פנסי המכונית, בוהה ובוהה וממשיך לחפש באופן נואש את הכפתור הקטן הזה עם האיקס.


מכירים את אלו?
בטח, כל אחד מכיר אותם.
"הפסקתי לראות טלויזיה", הם אומרים.
"התנתקתי מהכבלים!", הם מכריזים (מיד לפני שהם מצהירים שסחבק - ישראלי או לא? - מוריד את כל התוכניות שהוא הכי אוהב בחינם לגמרי בפרד האלקטרוני).
"נמאס כבר מהפרסומות", הם מתלוננים, ובצדק.
"הזבל שמציף אתכם מבוקר עד ליל ומזהם לכם את השכל", קורא לזה דרור פויר, בעוד הוא עצמו שוקד על הוספת תכנים (משובחים ככל שיהיו) לפח הזבל הגדול של האנושות, פח הזבל שאיש אינו טורח לרוקנו, פח הזבל שכל אדם יכול לצקת בו תוכן ללא כל הכשרה רשמית או גוף מכוון, פח הזבל שאותו לא מתסרטים, לא עורכים, לא מגיהים ובוודאי לא מסננים.

חלק גדול מ 12 מיליארד או יותר העמודים באינטרנט - בערך פי 2 ממספר האנשים בעולם, כולל אפילו את נמיביה - נכתב בידי אנשים משכילים ובעלי כשרון, ומהווה באופן כללי מה שאדם בר דעת היה בוודאי מכנה כ"לא זבל".
טוב, נו, אולי לא חלק גדול. חלק קטן. קטן מאוד. מזערי.

ועם זאת, אפשרי ואפילו רצוי לצרוך במידה מסוימת את אותו חלק קטן של תרבות אינטרנטית איכותית, כשם שאנו צורכים מדיות אחרות כגון מוזיקה, קולנוע, תיאטרון וספרות.

אז לא, אני עדיין לא ויתרתי על הבלוגים.
לא ניתקתי את האינטרנט ולא כיביתי את "מכשיר הטמטום" של המאה ה 21, המחשב.
כשם שלא ניתקתי את הלווין, לא כיביתי את הטלויזיה ולא הוצאתי אותה מן הבית.

את הסינון בין טוב ורע, בין מועיל ומזיק, בין ניצול זמן ובזבוז זמן, אני כבר אצטרך לעשות בעצמי - מה לעשות, החיים קשים בשנות האלפיים.

Labels:

Saturday, September 02, 2006

Bidirectional Blogging

When starting this blog, I was really concerned about writing a blog in two languages - English and Hebrew. As the title suggests, the problem is not using two different languages but actually writing in two different directions - left to right and right to left.

Unfortunately, searching the web for a little while yields no real solution for us bidirectional bloggers out there (I can only assume the Arabic blog scene propose no solution either).
I am sure some bloggers have sorted this out by themselves, while the others chose to align all of their posts to one direction or the other, regardless of the language they are written in. Another easy solution could be starting a different blog for each language. But that wasn't good enough for me.

The Blogger system, as I suppose other blogging platforms as well, provides the blogger with almost absolute control over the graphic design and layout of the page. It is done by means of a "Template" which is basically some html code with special tags inside, which is actually very similar to web scripting languages like ASP.

I was very pleased to find out Blogger allows javascript code to run from within the template, which among other things can solve this problem for all you bidirectional bloggers.

So, let's say you want to align every post with English text in it to the left, and any other post to the right. Here's how you do it:
First, start editing your template.
Then search for the special tag which looks like this:
<$BlogItemBody$>
Usually this tag is contained by a <p> tag, a <div> tag, or both. One of these containing tags probably has a class name used for graphic design purposes. In the template I worked on, that class name was "post-body". I assume this is the case in most templates.
The class name we found is the class we need to change from left to right or right to left.
For this you need to add the following piece of code to the end of the template:

<script language="javascript">

window.onload = applyRTL;

// This fucntion applies right-to-left style to posts
// that contains hebrew:
function applyRTL()
{
var arrDivs = document.getElementsByTagName("DIV");
var i;
var divPostBody;

for (i = 0; i < arrDivs.length; i++)
{
divPostBody = arrDivs[i];

if (divPostBody.className.toLowerCase() == 'post-body')
{
if (divPostBody.innerHTML.search(/[a-z]/) > -1)
{
divPostBody.style.direction = "ltr";
divPostBody.style.textAlign = "left";
}
else
{
divPostBody.style.direction = "rtl";
divPostBody.style.textAlign = "right";
}
}
}
}

</script>
This code will execute once the page and all of the posts in it were loaded, and will make every post that contains hebrew letters right-to-left and every other post left-to-right.
In case the class name from above is different in your template, change 'post-body' in the line:
  if (divPostBody.className.toLowerCase() == 'post-body')
to the name of the class in your template.

Since what that code does is basically search your posts for specific letters, you can change it to search for specific phrases and change the appearance of your posts according to their content.

Using client-side scripts inside your blog can do a lot of other cool stuff - any ideas anyone?

Labels: ,

Saturday, August 05, 2006

New Google Service

I've managed to put my hands on some top secret images of a very interesting new Google service... (enlarge for details)

I'll be the first one to sign up!






Hope you all enjoy it as much as I did :)
Yanir

Labels: ,

Monday, June 26, 2006

רוג'ר, מאחוריך

אז יצאנו מההופעה, עייפים אך מרוצים עד מאוד.
הייתה אחלה הופעה, עמדנו במיקום מצוין והסאונד היה מדהים - והשירים גדולים כפי שתמיד היו ותמיד יהיו.

הגענו לרכב ב 12:30, ופתחנו את הרדיו בפקקים.
כמובן שמיד חיפשנו תחנות שמדברות על ההופעה שזה עתה נגמרה, כי תמיד כיף לשמוע על עצמך ברדיו. רצה הגורל ונחתנו על תוכניתו של ניסים גרמה ברשת ב'.

ניסים מאוד התעניין בשמועות על השימוש של רוג'ר ווטרס בפלייבק במהלך ההופעה, בכדי לכסות על יכולות השירה שלו שידעו ימים יפים יותר.
שוחח ניסים עם מעין כתב מן השטח, ש"גם הוא זמר" לדבריו (כמובן שמעולם לא שמעתי את שמו). הזמר הלא ידוע אישר שאמנם לא שמו לב וזה היה עשוי היטב, אך בשיר אחד הוא הבחין בכך שייתכן וזהו פלייבק.

וכך ניסים גרמה:

"אני לא יודע אם הוא באמת השתמש בפלייבק, אבל אם כן הוא צריך להתבייש בעצמו. זה לא רציני".


וובכן, רוג'ר, תתבייש לך.
כנראה שיש לך עוד מה ללמוד כדי להגיע לסטנדרט הגבוה שדרוש כדי להצליח בארץ.

Labels: