Generally, if you are within the same class, the convention is to access the instance variable directly. An exception to this might be if the getter did some sort of error checking, and you wanted that error checking to occur each time you use the instance variable; then that work could be centralized in the getter, and the getter would be used. (And you'd put very descriptive JavaDoc comments on the actual instance variable so the next person that comes along knows to use the getter )
Although if you use access methods you can allow subclasses to override the behaviour.
I read a post in the Swing forum about someone who actually needed the base class to call methods, instead of using private variables. He ended up copy-pasting over 90% of the class he actually wanted to subclass.
Originally posted by Michael Bruesch: Have any time studies been performed to analyze the difference? I've done limited searching online on this topic but can't find anything conclusive.
I assume you means in terms of the time difference? I'm not sure if any such studies have been done. But, given todays processors, you are talking nanoseconds difference; likely just a couple of nanoseconds. And clear, understandable, and easy to maintain code should be a priority over extreme optimization. In the end, clear, understandable, and easy to maintain code will save hours (if not days or weeks) when changes or maintenance needs to be done. And that's optimization you can use.
There's a famous quote by Donald Knuth, who is a computer science guru, that states "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." (Knuth, Donald. Structured Programming with go to Statements, ACM Journal Computing Surveys, Vol 6, No. 4, Dec. 1974. p.268.) You can read more about optimization in this wikipedia article.
Joined: Sep 23, 2001
Oh yes, I will almost always choose readability over saving a few nano or milliseconds, but since they both seem equally readable to me I figured I'd see which one performed better.
Originally posted by John M Morrison: Keep your state variables PRIVATE!
Great advice, but the original question was about referencing a variable in the same class that it is declared in.
I am gonna throw my 2 cents in with using the get/set method calls rather than direct access. If those getters and setters can be overriden by child classes, then I would expect any behavior dependent on the properties those accessors represent to reflect the new behavior the child wants.