Private Variable

We make a private variable then public getter and setter. Why not just make variable public. Please think deeply dont go just for oops concept and acccessibility features,
[178 byte] By [Abhi_Upadhyaya] at [2007-11-27 8:31:33]
# 1

Because

1 - you may want to ensure that the variable is set a particular way

2 - you may want other functions to come into play when it is set.

3 - you usually don't want any bozo in the world to have access to your private variables in any manner they choose (yes, I am a control freak)

The arguments are very similar for gets too. It boils down to this: control, standardization, and information hiding.

morgalra at 2007-7-12 20:27:05 > top of Java-index,Desktop,Developing for the Desktop...
# 2

> Because

>

> 1 - you may want to ensure that the variable is set a

> particular way

> 2 - you may want other functions to come into play

> when it is set.

> 3 - you usually don't want any bozo in the world to

> have access to your private variables in any manner

> they choose (yes, I am a control freak)

You forgot one: Overriding

>

> The arguments are very similar for gets too. It

> boils down to this: control, standardization, and

> information hiding.

tjacobs01a at 2007-7-12 20:27:05 > top of Java-index,Desktop,Developing for the Desktop...
# 3

> Because

>

> 1 - you may want to ensure that the variable is set a

> particular way

> 2 - you may want other functions to come into play

> when it is set.

> 3 - you usually don't want any bozo in the world to

> have access to your private variables in any manner

> they choose (yes, I am a control freak)

>

> The arguments are very similar for gets too. It

> boils down to this: control, standardization, and

> information hiding.

Not really hidden if your method just returns it, though, is it? People seem to blindly hide every instance variable behind getter/setter methods, thinking that's "encapsulation" - it isn't. The argument goes that when you hide data behind an accessor method, you can change how that value is derived, under the covers, without having to change client code. Fair enough, but encapsulation goes further than that - it's preferable to not have to call a getter at all, but to ask the object to do whatever work you planned to do with that data. Otherwise, many classes become simply data holders, which isn't really object-oriented. There was a very long and interesting thread on this subject over at "New to Java" recently, but it got zapped for no discernable reason

Note, I'm not saying "just expose instance variables as fields, don't hide them behind methods", just saying "consider whether the method is necessary at all, and consider whether your client code really needs to ask for that data". Don't just blindly use accessor/mutators because you've heard it's a good principle

georgemca at 2007-7-12 20:27:05 > top of Java-index,Desktop,Developing for the Desktop...