Wednesday, March 22, 2006

Java: No block scope for access specifiers

Its already been 3 months since I have started coding in Java "fulltime" and being a C++ guy for almost 5 years, I sometimes wonder why the creators of Java did not think of having block scope for access specifiers. I have to precede every data member/method with the access specifier - private/public/protected. If I dont give anything it defaults to "friendly".

In C++ I can do:

public:
...
...
...
protected:
...
...
...
private:
...
...
...

In Java I have to do the following:
private ....
private ....
private ....
public ....
public ....
public ....
protected ....
protected ....
protected ....

Why, why, why? This keep daunting me - but then, this so called feature (or incapability) sometimes has its own advanatage:

Code becomes more pristine to read. I can look at a member variable or method and clearly tell its access restrictions without having to scroll up and down. Imagine I have 50 member variables that are private and I'm somewhere in the middle trying to read some data member and I have to scroll up to see what the specified access was. I have no clue otherwise (lets assume people do not follow coding standards for private/protected/public access specifiers). Think about the situations when people have multiple scopes opened and have declared member variables/methods scattered around the class. It becomes very difficult to read the code.

Many times I have seen people write code in C++ as:

private:
...
...
...
almost 25 lines
...
...
protected:
...
...
...
private:
...
...
...
protected:
...
...
...
The vicious cycle of declarations continues...

It becomes so difficult to read such code. Hence, its not so bad afterall in Java to completely avoid this obfuscated way of declaring member variables/methods. But still I wonder - was this a motivating factor for the creators to create it this way or was it some other factor?

It doesn't hurt to think of another possibility - since Java code is byte interpreted (the class files are all bytecodes), it might be a little too much pressure on the VM to store all the locations where the block scope access specifiers are for a particular data member/method. But then again - the compiler could use some intelligence and put in the correct access specifier for a member variable/method while parsing for the information and still maintain the same byte interface for the class code. This would definitely put more work on the compiler before it can get you a class file. Forget about people hitting you on the head for Java code to be slow, you will be whacked for suggesting to make the compiler also slow.

I guess at the end of the day it helps to have a cleaner looking code than a mushy spagetti kind of looking code as in C++. Goodbye block scope type specifiers.

0 Comments:

Post a Comment

<< Home