Friday, December 30, 2011

C++ and Automatic Garbage Collection

Programmers know about the mental state commonly referred to as “flow”. In this state, we are most productive, by a significant margin. This state is, of course, not limited to software development, and is well known in most creative pursuits. 
For example, I’m currently writing this article in a program called Scrivener, an excellent writing application targeted at professional writers - the kind that write novels, screen plays, etc. It has a special mode, called “full screen composition mode”, which I’m using at the moment.  In this mode, there is nothing on the screen except a blank white page. There are no formatting buttons, no word counts, no tasks bars, and certainly no talking paper clips. It is completely optimized for doing one thing, and one thing only - writing. Everything else is hidden away.
This Scrivener feature is there to help writers get into “flow” mode.
To enter this mode, you focus, completely, on the task in hand. And such a complete focus is not easy to establish. An incoming phone call, even if ignored, is more than enough to destroy it.

Focus is about saying no to the things which aren’t important right now. 

This is not a new concept, nor was it discovered by Steve Jobs. Learning to focus has been a very important step in Buddhist meditation techniques for thousands of years.
Of course, Scrivener is not the only tool that helps people focus. Another excellent tool more familiar to programmers is vi. This editor is not famous for ease of use, but once the learning curve is overcome, the editor is excellent at getting out of your way and becoming invisible. People report that vi helps them enter this productive zone, and I can attest to this myself.
Some programming languages also help you enter the zone more easily. Remember, getting into flow is completely focusing on a task. This is why for different tasks, some languages are better suited than others, with regard to flow. It is all about what the language chooses to hide from you. For a high level task, Python is probably a better choice than C, because it will be easier to enter a productive mental mode in Python without worrying about remembering to call free().
A great many people claim that the single greatest benefit for programming productivity in recent decades is automatic garbage collection, as seen in managed languages, such as Java and C#. Let’s ignore the fact that McCarthy invented it for LISP way back in 1959. This is an enormous benefit because today programmers focus on writing the code they want, and they don’t have to think about managing memory. The language hides it away.
A great many people, myself included, claim that C++ is a bloated language. They also claim, myself excluded, that C++ is terrible because of the manual memory management. It certainly is a great burden to manage memory manually - it is generally difficult to do correctly and it also makes it harder to enter the precious mental state we all covet, because it’s one more thing to worry about. But it is simply not true for C++.
It is true that in C you have to manually manage memory. It is true that 10 years ago, most people managed memory manually in C++. However, today this is no longer true.  Unfortunately, most Java/C# lovers, C++ haters, miss this fact.
More importantly, they miss out that the Java/C# promise is horrendously broken. Consider the following code snippet, taken from the book Release It  by Michael T. Nygard, page 33:

This Java code has  a bug in it. In this particular case, this bug caused thousands of people to wait for hours and hours for their flight and caused major financial damages to an airliner. 
The bug is that java.sql.Statement.close() can throw an exception. If it does, then the close method of the connection is never called, and a resource is leaked.
In Java/C#, code in the “finally” block has to be managed C-style. But C doesn’t have exceptions, and exceptions complicate resource management by an order of magnitude. Exceptions are critical. Exceptions change everything. There are work arounds in Java and C#, but they are just that - work arounds. They aren’t pretty!

The real problem here is that the garbage collector isn’t like a person walking around with a giant garbage can, cleaning up. A garbage collector, in Java/C#  at least, is like a person walking around with a giant plastic recycle bin, cleaning up after scattered bottles. He ignores all those copies of yesterday’s newspapers and the empty tuna cans.
A Garbage Collector should collect all garbage, and garbage is defined as any no longer needed resource. And a resource is not just a piece of memory (with the book-keeping that comes with it). A resource is also a file handle, a DB connection, a no longer needed synchronization lock, etc.
C++ shines here, because C++ has a built in garbage collector that manages all such resources. Yes, you heard that right. C++ has a built in garbage collector. In modern C++, most programmers never, ever, have to write “delete”. The “delete” keyword went the way of the dodo. It went the way of the goto. 
The same mechanism used for managing memory can be used for managing any kind of resource.

Focus is about saying no to the things which aren’t important right now

In Java, resource management is rarely not an important thing to think about.

Thursday, June 3, 2010

Saturday, March 27, 2010

Four Year. Go.

A bit naive, as always, but not a bad idea.

Friday, October 9, 2009

What You Have You Keep

The second law of thermodynamics states that in an isolated system, entropy is an increasing function. In his book, Do Androids Dream of Electric Sheep, Philip K. Dick talks about fighting entropy, or Kipple, as he calls it:
Kipple is useless objects, like junk mail or match folders after you use the last match or gum wrappers or yesterday's homeopape. When nobody's around, kipple reproduces itself. For instance, if you to go bed leaving any kipple around your apartment, when you wake up there is twice as much of it. It always gets more and more.

No one can win against kipple, except temporarily and maybe in one spot.

I've found that there is much truth in the Kipple Theorem. Just think of your house, which contiguously gets more cluttered over time. The same also happens to source code, if left to its own devices. It is also true of memory, which gets disordered over time. What was once clear and orderly, becomes obscure and messy.

Over the past couple of weeks, I've tried to always put something back in its place whenever I go from one room to another. When I do this with disciple, my house starts to look much better. A couple of days of slacking off, and the house looks once more like a total mess. And I don't ever remember making it a mess. It's just that kipple does multiple while you're asleep. Unless we take active, continuous action to combat it, kipple will always win.

Source code is no different. It grows smelly over time. No matter what your source control's log tells you, changes are constantly taking place. They make the code more unreadable, make methods more incomprehensible, and occasionally even introduced some bugs in unimportant locations.

The same is true when learning things, such as Japanese. I've studies nearly 400 kanji characters over the last couple of weeks. Unless I take active steps to maintain what I've learned, my neurons start getting all bogged down with kipple. That's why I am very fanatical about reviewing the items in my SRS software every day. Left alone, for even a little bit, the kipple raises its ugly head and starts to take over.

Kipple Fighting 101

When you learn chess, you basically have to study three different stages - opening, middle game and end game. For the opening stage, you basically memorize the known openings, which have already been studied thoroughly. During the middle game you need to understand basic principles and how to implement them. The end game part is usually kind of a mixture of the previous stages: memorize principles for different scenarios.

One of the most basic scenarios in the end-game is the one where you have a king and a rook and the opponent has only a king. It is very easy for you to win now. But, to make things explicit, the guiding principle is to always prevent the enemy from returning to territories from which he retreated. When the enemy king moves, you make sure he cannot move back to where he once was. You corner him into closer and closer areas.

In the endless chess game against kipple, the opposite is true:

What I have, I keep!

This means an endless game of maintenance. You've learned a new word - make sure you review it periodically. You finished cleaning the kitchen - make sure it stays clean. Constant vigilance is the key to winning this battle.

Whenever you go over source code, you will encounter kipple. It is your responsibility to engage it immediately. No matter what your current objective is, you must spend some of your time chasing and destroying the kipple. Otherwise, the kipple will take over the code base, and before you know it, no one on your team has a clue what does what.

Monday, October 5, 2009

Kill the CAPS LOCK!

The Caps Lock key can do wonders to wreak havoc in VI. You're in command mode, minding your own business, when all of a sudden all hell breaks loose. All because you pressed the caps lock key instead of the shift key.

For a long while I was reluctant to follow the plethora of tutorials on how to kill the caps lock key. The reason is that there are several cases where I thought it was very beneficial to actually use it to, well, lock the caps. For example, by tradition, definitions in C/C++ are written in all capital letters. I finally figured out how to get along without the evil key, as I will explain below:

g~w - capitalize one word
g~~ - capitalize the entire sentence
gU{motion} - capitalize motion

I still have some open issues. For example, to capitalize the word I just wrote, I have to go backwards ('b') and then capitalize it ('g~w') and then go back to insert mode ('A'). I'll be happy to learn of better options, options that take into account that I despite having to configure my setup. Nonetheless, I'm now much better off than I was with the occasional caps lock accident.

You can now make the caps lock key do something else, such as behave as a shift key or an esc key.

Further Reading: