Monday, February 11, 2008

Hungarian notation and Groovy

Comments and types are metadata and strictly not necessary to make a program, according to a popular post. Yes, they are not necessary to communicate with the computer, but that's not what we are trying to do here. For all but the smallest projects, we are communicating with people. The code should be understandable to others. And it doesn't hurt if it's understandable to ourselves either.

Hungarian notation was a popular in C to show the type of a variable in its name, for instance:
int nSize;
char cChar;

I never liked this, because if I change the type of a variable I would also have to change its name everywhere. But with dynamically typed languages, I some times get in trouble because I forget what type a variable is. So, I started to think if maybe Hungarian notation could be useful.

For example, consider the following dynamically typed Groovy code:
(1) def x = "100"

the following statically typed Java code:
(2) String x = "100";

and this statically typed Java code:
(3) int x = "100";

Which is most easy to understand?
(3) is easily recognized by both humans and the compiler as an error.
(1) and (2) are valid code. But 20 lines down the code, you have forgotten what type x is and write:
x++

Then (2) will give you a compiler error, but (1) won't be detected until runtime.

Does this mean I'm against dynamically typing? No. But if we remove the static type checking, I think we should use other means to communicate that information. For instance, it is a bad idea to call a String x. This would be much better:
def s = "100"

In Groovy, I often use maps instead of creating a new class:
def map = [:]
map.x = 100
map.y = 200

How am I supposed to remember what the map contains down the road?

I don't want to remember, I want the map to remind me! I have enough things to think about, I don't want to remember the type of every variable too!

I have a lame technique I use to not forget important things: I try to make them remind me instead of having to remember them. For instance, if I take off the lid to fill gas in the car, I put the car keys by the lid. That way, it's impossible for me to forget it. I cannot drive off without seeing the lid and remember to put it on. I use similar techniques at work. This reduces stress and helps me to concentrate, because I don't need to remember so much.

Applying this technique to Groovy gives this code:
def point = [:]
point.x = 100
point.y = 200

So, I am not advocating Hungarian notation, but good naming conventions that communicate what we need to know.

Programming is more about communication than how fast you can crank out code.

No comments: