Thursday, July 9, 2009


When I was using Visual Basic I never really got to grips with functions. I knew how to use them, and liked them, if someone else wrote them. For example the function log(x) returns the logarithm of x, and is often handy to use. But I took the view that all the useful functions had already been written, and I could not see why I should ever need to write one myself.

On the other hand, I found simple subroutines very useful, especially for chunks of code which might be called in more than one circumstance. But I never made a conceptual link between a function and a subroutine.

In Java, what VB calls a function is called a method, and what VB calls a subroutine is called a void method, so one is led to think about the similarities between the two constructs.

My stereotype of a function is a lump of code with a single unambiguous purpose. For example the function log(x) would never be used for anything except to calculate the logarithm of a number. It was only when I started coding in java that it occurred to me that what is returned by a method might be like a bi-product of code, the principal purpose of which is to do something completely different.

For example in my Java Math Test, I have an applet which displays the user interface, and supporting classes which do the grunt work, including most recently the data connection. I had got beyond testing with the command line applet viewer, and wanted to try the applet in a regular browser calling files from a web server. As I could no longer use standard output for debugging messages, I wanted to display a message in a GUI object on the applet itself.

Most of the stuff done by my supporting classes is done by calling void methods. But in order to check whether or not a connection had been made, I dressed up the connection code in a method returning a string. The code looked as follows:

public String dataConn() {
try {
String strconn = "jdbc:derby://";
liveconn = DriverManager.getConnection( strconn );
smt = liveconn.createStatement();
buffer = "connection succeeds ";
} catch(Exception ex) {
buffer = "connection fails ";
return buffer;

And it was called by the simple expression:


Where addItem is a method on the main applet which adds short diagnostic messages to a string of messages and displays them in a text label. On the surface (at least from where it is called) it looks as if dataDriv is a method or function designed to do something with text, whereas in fact it's primary purpose is to make a data connection, and the text it returns is a bi-product for diagnostic purposes.

No comments: