Thursday November, 03 2005

The not so private privacy of Java    \\ coding

Today I discoverd that a private variable in Java didn't mean exactly what I thought it meant.

We recently ran into a bug in Roller that was derived from the fact that Hibernate 3 doesn't like it when you access member variables directly rather than through bean style getXXX() methods. The reason for this is because Hibernate likes to use proxies and lazy loading to fetch data only when it thinks it's needed. While debugging this problem I discovered that the "private" keyword in Java worked a little differently than I had thought.

Up until now I had believed that "private" meant that access was limited to within a given object, i.e. an instance of a Class. However the truth is that "private" only limits access to a Class and whether or not the Class has been instantiated is irrelevant. example ...

public class Foo {

  private String myAttribute = null;

  public String getAttribute() {
        // maybe I want to perform some logic here?
        if(this.myAttribute == null || this.myAttribute.length() < 1) {
                return "you need to set a value for this attribute!!";
        } else {
                return this.myAttribute;
        }
  }

  public void setAttribute(String attr) {
        this.myAttribute = attr;
  }

  public void someMethod(Foo otherFoo) {

        String memberVar = null;

        // this directly accesses a member attribute of the object passed in
        // I had thought this was not possible
        memberVar = otherFoo.myAttribute;

        // this is what I would normally do and until today
        // I had thought this was required
        memberVar = obj.getAttribute();

        // or maybe you prefer to write data?
        otherFoo.myAttribute = "huh?";
  }

}

I'm not sure why I had never realized this before, it's actually written very plainly in the Java Tutorial ... "A member's access level determines which classes have access to that member, not which instances have access."

What I am wondering now is, why not provide some kind of instance privacy? Wouldn't it seem like a good idea to allow an instance to shelter it's member attributes completely? I suppose there are very few cases where the situation I mentioned above would cause problems, but still, for some reason I feel like I've lost some privacy.

Posted by gconf at Nov 03 2005, 05:48:19 PM PST | Permalink | Comments (0)
Comments:

Post a Comment:
  • HTML Syntax: NOT allowed

Search

The Grabbag

Powered by
Roller Version 4.0.1.1 (BSC)
© copyright gconf ... don't copy me!