Musings in real time

Tags - Categories : All | Art | Books | Family | Hacks | Java | JavaRanch | Linux | Philosophy

Some people laugh when they see my code, because I insist on the (supposedly old-fashioned and unnecessary) practice of using a "wart" to denote Java member variables. For example, I'll write

public class Person {
    private String m_name;
    private Date m_dob;
    ...

The laughers usually see this as a hangover from "Hungarian notation", in which the data type of a variable is encoded in its name. The merits of Hungarian notation have been debated endlessly, so I won't go into that here. Besides, my warts are not Hungarian: they're scope warts.

Scope warts prevent scoping errors; perhaps more precisely, they prevent accidental variable hiding. What's wrong with this code?

public class MyVector {
    private int size;
    private Object[] data;
    public int itemCount() { return size; }
    ...
    public void addAll(MyVector v) {
        ensureCapacity(itemCount() + v.itemCount());
        int size = v.itemCount();
        for (int i=0; i<size; ++i) {
            data[size++] =v.data[i];
        }
    }
}

Can you see it? That last line of code is incrementing the local variable "size", but it actually means to increment the member variable. Ooops. The loop will run until it gets an ArrayIndexOutOfBoundsException.

Scope warts would have prevented this. If we rename the member variable "m_size", then there'd be no name collision. Furthermore, collisions like this would never happen. A whole class of sometimes hard-to-find errors would be eliminated at the source.

Other people eschew the warts, but insist that all member variable accesses be made via the "this" reference. I don't like that, personally -- too much discipline. Scope warts require you to name variables a certain way, and then everything else takes care of itself. The "this" solution requires you to do some extra typing every time you access a member -- which is a lot of work. Anytime you ask people to do extra work, you're asking for trouble.

Why do I bring this up today? Because I just closed a bug report from a user. Seems a class I wrote in a moment of weakness -- perhaps just after someone had made fun of my warts -- didn't use scope warts, and contained a bug just like the one described here! So you see, this happens in real life. I'm going to stick with my warts; they've served me well.