Suggestion

Extending the Java programming language with the feature “locally defined global variables” or “implicitely global variables”

1. Local Variables

Global variables are mostly used when more then one method of a class needs access to them. Some global variables are being accessed by only one method – they use it as their “memory” to transfer data between calls. Then the variable – used inside the method – must be defined outside the method (usually as private). This contradicts the principle of locality ("things belonging together should be located nearby"):

private Object memory;
…
void method() { …
	if (memory == null)
		… // first call
	else
		… // remember information from earlier calls
}           

It would more correspond with the principle of locality if the variable could be declared inside the method – closer to its usage. Then it should be “implcitely global”:

void method() { …
	private Object memory;
	if (memory == null)
		… // first call
	else
		… // remember information from earlier calls
}

2. Parameters

Many classes has parameterised constructors saving the parameter values in global variables, in order to make them accessible for other methods:

private int value;
protected Object reference;
…
public MyClass(int value, Object reference)  {
            this.value = value;
            this.reference = reference;
} 

This pattern – written very frequently – could be abbreviated if global variables could be defined locally (as parameters):

public MyClass(private int value, protected Object reference) {}
// equivalent to code above

This should be allowed for any method:

private setValue(private int value) {}

is equivalent to

private int value;
…
private setValue(int value)  {
	this.value = value;
}

Of course, any other method would have access to any implicitely global variable just as to explicitely global ones.

3. Suggestion

This feature might decrease readability of a class: Usually its global variables are defined in the beginning. The reader can find all of them at one place.

However, he cannot find the inherited variables at this place. Also the same principle is not applied for local variables (unlike Pascal or Ada, requiring all local variables to be defined at the beginning of a method).

So I suggest modifying the syntax of the Java programming language to allow access protection (private, protected, package or public) for local variables (including formal parameters). The semantics of this feature should make them global with the corresponding access protection (package means “default”).

Multiple defined global parameters (with the same name, type and access protection) should refer to the same global variable. Multiple defined global variables (with the same name, possibly in different methods) should be an error.

In order to maintain consistency, the access protection package should also be allowed for global variables with the meaning of “default”.