This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes private variables and accessor methods? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "private variables and accessor methods?" Watch "private variables and accessor methods?" New topic
Author

private variables and accessor methods?

Mitch Krah
Ranch Hand

Joined: Sep 06, 2004
Posts: 41
Can someone explain to me the logic behind making varaiables private (so that other classes CAN NOT access or change the variables) and then adding accessor methods (so that other classes CAN access or change the variables)??? I don't get it? There has to be a reason because it is in every JAVA book I am reviewing. But, it appears inherently counter productive.

Help?

Thank you,
Mitch
Nick George
Ranch Hand

Joined: Apr 04, 2004
Posts: 815
It's for that reason that I made a deal with myself that anytime I have both an get and a set, I just go ahead and make it public. The logic, however, is (as I understand it) 'encapulation,' meaning that if you want to change how a class represents its data internally, you can do so without having to change all the code that uses the variables you've changed.


I've heard it takes forever to grow a woman from the ground
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Here are two examples to make the concept of encapsulation clearer. First, you may want to restrict the acceptable values of a property.If you exposed name directly, you'd have to trust all clients of your class to do these checks. If you later wanted to add another validation check, you'd have to change every case where it's set. With the accessor, you only have to change one piece of code to affect all clients at once.

Now think what you'd have to do if you changed the name property to two properties -- firstName and lastName -- internally. All code that accesses name must now be changed to handle the change. With accessors, however, you can add new accessors for first and last name and keep the old accessor for backward compatibility.You might ask "What if I have a property that doesn't need any of these checks or handling?" If you decide to skip accessors and use public fields, you are setting yourself up for a headache if you ever need to add anything like the above. You're painting yourself into a corner.

By using accessors by default, you'll be more free to modify how your classes work in the future without changing all the code that uses them.
Mitch Krah
Ranch Hand

Joined: Sep 06, 2004
Posts: 41
OK then. Wow! That was a little hard to follow for a beginner. But, I get your meaning. Sounds to me like it is good practice, so I will continue to follow the conventions as called out in the text and confirmed by your examples.

Thank you for your help.

Mitch
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
Deitel pere et fils mention another good reason to always use setXXX() methods, even within the class containing the variables: If a variable winds up with a bad value, you have one place to check out and possibly add more validation code.
[ November 13, 2004: Message edited by: Mike Gershman ]

Mike Gershman
SCJP 1.4, SCWCD in process
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

One more thing that no one here has mentioned: a lot of newbies -- and even some Java books -- make the mistake of assuming that the normal order of things when you add a member to a class is to immediately add a getXXX() and a setXXX() method. But that's wrong -- you should add neither. If, at some time in the future, you need to read the member's value outside of the class, and allowing that seems like a good design decision, then you can add a getXXX() method. Similarly for changing the value of the variable with a setXXX() method, but setXXX() methods are, and should be, considerably rarer.

I said that you should make sure it's a good design decision before adding getXXX(), because oftentimes if you feel you need to add such a method, what the code is telling you is that you're writing a method on the wrong class: maybe the code that needs to call getXXX() actually belongs in the class where XXX is defined!


[Jess in Action][AskingGoodQuestions]
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
Ernest:

You made a point about providing public accessor methods.

Deitel suggests that even private access to instance variables should go through accessor methods so that changes to how the information is stored or what validation is performed can be implemented in one place in the program. Do you agree?
Joyce Lee
Ranch Hand

Joined: Jul 11, 2003
Posts: 1392
Originally posted by Mike Gershman:
Ernest:

You made a point about providing public accessor methods.

Deitel suggests that even private access to instance variables should go through accessor methods so that changes to how the information is stored or what validation is performed can be implemented in one place in the program. Do you agree?


I think this is called Self Encapsulation. Is this a good practice?
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Joyce Lee:


I think this is called Self Encapsulation. Is this a good practice?


I agree with Martin Fowler here: Sometimes it's handy, but when it does, it's quite easy to refactor the code from direct access to self encapsulation. Therefore I'm not using it as the default.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I'll vote with the idea asking yourself if a getter is necessary. I inherited some code like this:

First I removed the getters (and setters) and gave widget the responsibility of knowing whether it matches. Now we can add rules like ignoring case or allowing close matches in one reasonable place. Second I removed the oddball matches() method and used a standard equals().

An object is "data plus behavior" but there's no rule that says it ever has to let you know anything about its data!
[ November 14, 2004: Message edited by: Stan James ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: private variables and accessor methods?