John Chamberlain
Developer Diary
 Developer Diary · You Heard It Here First · Monday 1 March 2004
Principles of Programming: Pass by Reference
A cardinal rule of programming is to pass by reference rather than value. One of the reasons for this is that when you pass by value you cause a copy of the variable to be created. This is bad because now there are two representations of a single thing. In principle if you have one thing there should be one representation of it. In object oriented programming this idea is obvious and noone thinks twice about. Who would go to the trouble of cloning an object just to pass it to a function that needed information from the object? Noone. Yet, all these same programmers routinely make copies of primitive values when they are passed. Why? Because it is easier.

By this you can see the ill design of languages of Java and C. The former makes it impossible to pass primitive values by reference directly and the latter makes it inconvenient because the default is to pass by value. In fact, the default should be to pass by reference. The mistaken construction of these languages force programmers into poor practices like passing by value.

In Java the only way to pass a primitive value by reference is to use an array. Usually only a single storage location needs to be passed so a one-element array can be used. I call such an array an "egg" because when it is dereferenced the 0 looks like an egg. For example,

     boolean zGetValue( int[] eggValue, StringBuffer sbError ){
         try {
             eggValue[0] = 1234;
             return true;
         } catch(Exception ex) {
             sbError.append("failed to get value: " + ex);
             return false;
In this example the integer value is returned inside of an egg, a one-element array. Because I use a one-based arrays (another principle) when I see a zeroeth element being dereferenced I know it is probably an egg. Here the egg is made obvious by the presence of the hungarian prefix "egg" as well. The typical programmer when coding something like this would not bother with an error trap and returning a boolean to indicate success or failure. They would just return the integer as the return value. The consequences of this is that if an error occurs the user either gets no error message or a cryptic error message because by the time the error is finally trapped way upstream the context in which the error occurred has been lost. Here I capture the error context immediately and store it in a string buffer which is passed backwards (by reference of course).

The principles of programming build on one another. Passing by reference is intertwined with one-based arrays and error handling and everything else. When you follow the principles the program grows harmoniously and when you don't, well, you get cryptic error messages.

return to John Chamberlain's home · diary index
Developer Diary · about · · bio · Revised 1 March 2004 · Pure Content