wood burning stoves 2.0*
The moose likes OO, Patterns, UML and Refactoring and the fly likes About Getters & Setters Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "About Getters & Setters" Watch "About Getters & Setters" New topic
Author

About Getters & Setters

Debbie Dawson
Ranch Hand

Joined: Aug 31, 2010
Posts: 30
I have heard that using Getters/Setters is "evil"! (For example JavaWorld: Why Getters and Setters are Evil)

So, if this is true, then what is the workaround?

I am still struggling in going from book knowledge to applying OOP to a real application.

(With my Procedural background, I would think Accessor Methods are great, but it sounds like if I want to be a seasoned OOP person, I need to re-think how I design things?!)



Debbie

Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
Encapsulating object data with JavaBean get/set methods is good and should be implemented. Many Java-based frameworks follow this paradigm as well.

In the end it is a design decision, for programmers and engineers under my supervision JavaBean get/set methods are mandatory in class design.

However, there are rare situations to this design style where it is better to expose one or two data variables publicly. It depends.
Debbie Dawson
Ranch Hand

Joined: Aug 31, 2010
Posts: 30
Jimmy Clark wrote:Encapsulating object data with JavaBean get/set methods is good and should be implemented. Many Java-based frameworks follow this paradigm as well.

In the end it is a design decision, for programmers and engineers under my supervision JavaBean get/set methods are mandatory in class design.

However, there are rare situations to this design style where it is better to expose one or two data variables publicly. It depends.


1.) I was asking in language independent terms (i.e. not just Java).

2.) Wow! Most articles I have read (e.g. JavaWorld: Getters and Setters are Evil!) strongly disagree with what you just said...



Debbie

Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
Exactly how many "web" articles have you read about this topic?
Debbie Dawson
Ranch Hand

Joined: Aug 31, 2010
Posts: 30
Jimmy Clark wrote:Exactly how many "web" articles have you read about this topic?


The general consensus I have gotten speaking to senior-type OOP developers and the articles I have read from the same lot seem to almost always say the same thing... "Getters and Setters are in direct conflict with the basic principle of Encapsulation in OOP."

The article I posted doesn't say to never use them, but it clearly shows why it is a poor choice.

I'm no expert, but that article seems spot on...

Poking into an object is just like using global variables to access any data, any time, from any where. That's what you do in BASIC, right?

I thought the whole idea of OOP was to hide the implementation and allow access via methods and by passing the entire object...


Debbie

Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
The author's opinion that "accessors violate the encapsulation principle" is questionable. Actually, the accessor method paradigm serves to
protect (encapsulate) the data from other objects. Client objects must "ask" the object for its data rather than accessing it directly.
Forcing client objects to use accessor methods only will enable you to add any needed behavior in the future.

Exposing data publicly is a violation of the theory of encapsulation.

Again for emphasis, object-oriented design is a "design concept." And there are a many different and sometimes conflicting interpretations of
what things "mean" and what is "best." For example, Computer Science professors that have been teaching for 20 years and practioners working in
commercial industries for 20 years may see OOAD differently. There are other examples.

Aside, if you look at Struts or Hibernate frameworks you will find prime examples of why and how get/set methods are needed.

Aside, undisciplined programmers may tend to look at get/set methods as a waste of time and unneccessary. They also
tend to produce classes without JavaDoc comments and rush to start coding without proper time for analysis and design.
This style of "senior" OOP eventually results in "mystery" code that is difficult to debug, enhance and teach.
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Debbie Dawson wrote:The general consensus I have gotten speaking to senior-type OOP developers and the articles I have read from the same lot seem to almost always say the same thing... "Getters and Setters are in direct conflict with the basic principle of Encapsulation in OOP."

I find that [ contrary to my experience ] , and contradictory to encapsulation.

What *are* issues are things like not following the Law of Demeter (or, as I prefer, the Strongly-Worded Suggestion of Demeter), or returning specific implementations instead of interfaces, or not returning immutable versions or copies of underlying objects. Those are very different things.

It's also very important to remember a couple other points: Java is *not* a great example of an OOPL, and practicality often outweighs purity.

Classes *should* be self-contained, and we should program Java like it's a functional language. But it isn't.

[ UD: edited ]
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61662
    
  67

[ That makes no sense. ]. Please take careful note of who wrote the article to be sure to never read anything else that he has written.

[ UD: edited ]


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

(Well, I dunno... he's not always totally ridiculous, but did have a tendency to write deliberately inflammatory articles back in those days, like the whole XML thing he was on about around the same time. Most of us chalked it up to trying to drum up traffic.)
Debbie Dawson
Ranch Hand

Joined: Aug 31, 2010
Posts: 30
Bear Bibeault wrote:[ That makes no sense. ]. Please take careful note of who wrote the article to be sure to never read anything else that he has written.


Care to elaborate and education the Java newbs of the world?

Debbie

[ UD: edited ]
Debbie Dawson
Ranch Hand

Joined: Aug 31, 2010
Posts: 30
David Newton wrote:
Debbie Dawson wrote:The general consensus I have gotten speaking to senior-type OOP developers and the articles I have read from the same lot seem to almost always say the same thing... "Getters and Setters are in direct conflict with the basic principle of Encapsulation in OOP."

That's [ contrary to my experience ] - and contradictory to encapsulation.

What *are* issues are things like not following the Law of Demeter (or, as I prefer, the Strongly-Worded Suggestion of Demeter), or returning specific implementations instead of interfaces, or not returning immutable versions or copies of underlying objects. Those are very different things.

It's also very important to remember a couple other points: Java is *not* a great example of an OOPL, and practicality often outweighs purity.

Classes *should* be self-contained, and we should program Java like it's a functional language. But it isn't.


So please explain why this author's article (and position) are [ don't make sense ] to you...

I thought he made a lot of good points for the little I know...

Debbie

[ UD: edited ]
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

If you want to be a "seasoned OOP veteran", program in OOPLs for a decade or two, learn more than one OOP paradigm, use better OOPLs than Java and PHP. Code fiendishly: how's your registration app going? Have you coded it in a half-dozen ways yet? Until you do, why bother arguing about what the "best" way is? Who cares? Experiment. See what works, and what doesn't. Read all the articles you want--but if you're going to hand-wave with an article and "general consensus" don't be surprised when people are more amused than engaged. (And this is nothing--try this on LtU and see what happens; there even I tread only lightly. But I'd genuinely enjoy watching you defend PHP as a language there.)

Debbie Dawson wrote:The article I posted doesn't say to never use them, but it clearly shows why it is a poor choice.

No, it really doesn't: it rails against exposing internal details (sort of, see below)--but this is the result of stupid programmers, not getters/setters.

The Article wrote:It seems natural, then, to mimic a struct by building class definitions with virtually no methods and nothing but public fields.

Maybe yet *another* decade before this article was written it seemed natural? Or maybe this was true of non-OOP devs coming to Java?

Even then--Java is not the only OOPL. Some OOPLs don't even *have* a concept of data hiding--like Smalltalk. Smalltalk is probably *the* prototypical OOPL. So this article is approaching the problem from a singular, narrow focus at the outset.

Then there's this section on when it's "okay" to use getters/setters...
The Article wrote:it's okay for a method to return an object in terms of an interface that the object implements because that interface isolates you from changes to the implementing class

So... I could return a Collection, right? It's an interface.

Which gives me direct access to backing object, which I can keep a reference to elsewhere, modify, do whatever I want with. Which could cause no *end* of troubles in the class itself.

That violates encapsulation, and the Strongly-Worded Suggestion of Demeter. That he doesn't even *mention* Demeter is a *BIIIIIG* reason to treat the article with suspicion--he leaves out the *most* important topic, and in fact obfuscates its importance by claiming that by exposing an interface that accessors are suddenly "ok".

The article is an argument for functional programming, not against getters/setters, and does a poor job. But it did what it was designed to do.

[ UD: edited ]
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Alan Holub can be quite a character, and he definitely has taken some extreme stances over the years in his articles. Note that around the same time, he wrote another JavaWorld article called "'extends' is Evil".

I haven't even read the article that we're discussing here (maybe I read it when it came out, but who remembers?) but I'll give you my viewpoint: There's nothing whatsoever intrinsically wrong with accessor/mutator methods, but the notion of always adding get/set methods for each member variable -- which some people do automatically -- is crazy, and perhaps that's the "evil" Alan's getting at. Back when he was writing, there were still IDEs that would automatically create those methods by default for any member variable you added, and that's ridiculous.

A class should have "get" methods for precisely those properties that would be useful to read, and "set" methods only for those that would be useful and safe to set. Should these, or do these, correspond one-to-one with the instance variables of the class? Generally not. You'll read more than you can set, and some properties don't correspond to a single member variable but rather some combination.


[Jess in Action][AskingGoodQuestions]
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61662
    
  67

Ernest Friedman-Hill wrote:A class should have "get" methods for precisely those properties that would be useful to read, and "set" methods only for those that would be useful and safe to set. Should these, or do these, correspond one-to-one with the instance variables of the class? Generally not. You'll read more than you can set, and some properties don't correspond to a single member variable but rather some combination.

Exactly this.
Debbie Dawson
Ranch Hand

Joined: Aug 31, 2010
Posts: 30
Well, first off, like everything OOP related, the more I read the more confused I get! (I just read all of the comments below that article and it was like 50% agreed and 50% disagreed. So who do you believe?!)

Why might Getters/Setters be bad in my own words?

Hmmm...

I think the main thing is that you are *supposedly* supposed to keep "data" and "behavior" close together. Well designed classes have the "right data" and the "right actions" in the same class. If you have a class "Order", you would ideally not only have a properties called "subTotal" and "salesTaxRate" but a method called "calculateSalesTax()" and "calculateOrderTotal()".

You would want to avoid having and using "getSubTotal()", "getSalesTaxRate()", then reading said values into another space (be it a class or wide-open-range), calculating the "orderTotal" and then using "setOrderTotal()" back in the original "Order" class. (Such a scenario is how we used to do things in BASIC!!)

I think that is the #1 scenario that I took from the article and comments I've seen online.

Does that mean that you never need to Get/Set properties in an object? No. But I think the author's points were:
1.) Keep "data" and "actions" as close together as possible (read "encapsulation")
2.) When an Object cannot complete something on its own, pass the ENTIRE OBJECT to an Object that can, versus cherry-picking Attributes and treating them like global variables.

If you have coffee (Attribute) in a Cup (Object), and you want to warm up your coffee, you do not pour the coffee (get) into your hands (rebel environment) and put it in the microwave (another Object) and then when it is warm transfer it back (set) to your Cup?! "In the real world" you would simply take the coffee (Attribute) in the Cup (Object) and place it in the Microwave (another Object) so that you can Warm Up (Microwave Method) Coffee (Cup Attribue) in your Cup (Object), right?!


If you want to be a "seasoned OOP veteran", program in OOPLs for a decade or two, learn more than one OOP paradigm, use better OOPLs than Java and PHP.


Well the reason I'm here is to chop that down from two decades to just 9 years?! :wink:


Code fiendishly: how's your registration app going?


I am making decent progress on my understanding of how OOP works, and have a decent strategy that I hope to implement here shortly...


Have you coded it in a half-dozen ways yet? Until you do, why bother arguing about what the "best" way is?


Same reason I don't jump on the first plane for Europe when I want to make my first trip there and see certain things a certain way.

"Cowboy Coding" never got anyone - who is serious - very far in life...


See what works, and what doesn't.


I'm asking people what they think works and what doesn't so I don't "re-invent the wheel"!!


Read all the articles you want--but if you're going to hand-wave with an article and "general consensus" don't be surprised when people are more amused than engaged. (And this is nothing--try this on LtU


What is that??

But I'd genuinely enjoy watching you defend PHP as a language there.)


I never said PHP was a "real" OO language. I just asked why you find Java so superior.


Debbie Dawson wrote:The article I posted doesn't say to never use them, but it clearly shows why it is a poor choice.

No, it really doesn't: it rails against exposing internal details (sort of, see below)--but this is the result of stupid programmers, not getters/setters.

The Article wrote:It seems natural, then, to mimic a struct by building class definitions with virtually no methods and nothing but public fields.


So I'm here to not become a *stupid programmer*...


Maybe yet *another* decade before this article was written it seemed natural? Or maybe this was true of non-OOP devs coming to Java?

Even then--Java is not the only OOPL. Some OOPLs don't even *have* a concept of data hiding--like Smalltalk. Smalltalk is probably *the* prototypical OOPL. So this article is approaching the problem from a singular, narrow focus at the outset.

Then there's this section on when it's "okay" to use getters/setters...
The Article wrote:it's okay for a method to return an object in terms of an interface that the object implements because that interface isolates you from changes to the implementing class

So... I could return a Collection, right? It's an interface.

Which gives me direct access to backing object, which I can keep a reference to elsewhere, modify, do whatever I want with. Which could cause no *end* of troubles in the class itself.

That violates encapsulation, and the Strongly-Worded Suggestion of Demeter. That he doesn't even *mention* Demeter is a *BIIIIIG* reason to treat the article with suspicion--he leaves out the *most* important topic, and in fact obfuscates its importance by claiming that by exposing an interface that accessors are suddenly "ok".


What is the "Strongly-Worded Suggestion of Demeter"??

The article is an argument for functional programming, not against getters/setters, and does a poor job. But it did what it was designed to do.


Okay.


I never said I was entirely for or against what this author published. I did say it sounded like it had merit. If you [ don't like ] the author or his views, fine, but you come across like I'm making these controversial statements.

Debbie

[ UD: edited ]

Debbie Dawson
Ranch Hand

Joined: Aug 31, 2010
Posts: 30
Ernest Friedman-Hill wrote:Alan Holub can be quite a character, and he definitely has taken some extreme stances over the years in his articles. Note that around the same time, he wrote another JavaWorld article called "'extends' is Evil".


Isn't it?

My "Head First: Design Patterns" book said something like, "Favor Composition over Inheritance".


I haven't even read the article that we're discussing here (maybe I read it when it came out, but who remembers?) but I'll give you my viewpoint: There's nothing whatsoever intrinsically wrong with accessor/mutator methods, but the notion of always adding get/set methods for each member variable -- which some people do automatically -- is crazy, and perhaps that's the "evil" Alan's getting at.


Sounds reasonable.


Back when he was writing, there were still IDEs that would automatically create those methods by default for any member variable you added, and that's ridiculous.


I agree.


A class should have "get" methods for precisely those properties that would be useful to read, and "set" methods only for those that would be useful and safe to set. Should these, or do these, correspond one-to-one with the instance variables of the class? Generally not. You'll read more than you can set, and some properties don't correspond to a single member variable but rather some combination.


Okay.

What did you think about my two examples above? (i.e. Order example and Coffee example)



Debbie
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Debbie Dawson wrote:
Have you coded it in a half-dozen ways yet? Until you do, why bother arguing about what the "best" way is?
Same reason I don't jump on the first plane for Europe when I want to make my first trip there and see certain things a certain way. "Cowboy Coding" never got anyone - who is serious - very far in life...

The less you code the less you'll learn. Period. *START CODING*. Who *cares* if you "cowboy code" 500 lines of code?! Your purpose should be to start figuring out what works. IMO you should have implemented this two or three times already. I don't understand why you won't. I don't understand your attempts to learn how to program without programming. I don't understand your reluctance to experiment. I don't understand your reluctance to throw away your work--at this stage of the game it is what should, and will, happen. We started talking about this, what, three weeks ago? You want to become a seasoned OO programmer? Program.

And this is nothing--try this on LtU
What is that??

Lambda the Ultimate.

I never said PHP was a "real" OO language. I just asked why you find Java so superior.

Java is an abomination--PHP just happens to be worse.

What is the "Strongly-Worded Suggestion of Demeter"??

Google Law of Demeter.

[ UD: edited ]
Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
Debbie, the JavaBean get/set method style was created for simple "data" classes. It should not be applied to complex classes that contain processing algorithms or any type of behavior/functionality.

David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Jimmy Clark wrote:Debbie, the JavaBean get/set method style was created for simple "data" classes.

That's not really true; JavaBeans were created to allow tooling and other beans to use and manipulate objects, and to foster application composition. The relative simplicity or complexity of the components was never a consideration--this was one of the selling points of JavaBeans: a complex application or component could be manipulated and plugged in the same way as a simple one.

http://www.oracle.com/technetwork/java/javase/tech/index-jsp-138795.html
Debbie Dawson
Ranch Hand

Joined: Aug 31, 2010
Posts: 30
David Newton wrote:The less you code the less you'll learn. Period. *START CODING*. Who *cares* if you "cowboy code" 500 lines of code?! Your purpose should be to start figuring out what works. IMO you should have implemented this two or three times already. I don't understand why you won't.


I have written some code, but nothing I'd post here (and not just because it is lowly PHP).

I'm trying to get my hands around several concepts that books and tutorials and most of the schmucks online don't have a clue on. The past couple of days I think I'm getting a little traction. And as I think and code a tiny bit, stop and ponder and research and ask more questions like here. (Lines of code do not equal being "productive".)


I don't understand your attempts to learn how to program without programming.


I don't think like most people do. I can't explain how I learn, other than to say I know how to learn and when I get there I know a topic very well. (I'm an abstract thinker...)


I don't understand your reluctance to experiment. I don't understand your reluctance to throw away your work--at this stage of the game it is what should, and will, happen.


I have written tiny bits and threw them away, and did something different, but I don't think my code is worthy to discuss yet. (I spent several days getting my hands around arrays and POST!)


We started talking about this, what, three weeks ago? You want to become a seasoned OO programmer? Program.


I am! Just slowly.

(When you know nothing about the web - like me - there is a lot to learn between HTML, CSS, HTTP, PHP, OOP, Design Patterns, Java, etc.)


And this is nothing--try this on LtU
What is that??

Lambda the Ultimate.

What's the origins of that website?

Looks like its from MIT or something?!

There is no "About Us" link...


I never said PHP was a "real" OO language. I just asked why you find Java so superior.

Java is an abomination--PHP just happens to be worse.


In case you didn't get the memo, you are on a website dedicated to Java?! :confused:


What is the "Strongly-Worded Suggestion of Demeter"??

Google Law of Demeter.


And here I thought you were talking about Autumn and Persephone!

That is a pretty cool law. (In fact, that's why I was/am suspicious of Getters/Setters.)


Do you really believe you can shortcut the process? I don't.


I don't think the fact that 80% of goods in Wal-Mart being made in China is a good thing either, but neither things have anything to do with the conversation at hand!

You are absolutely correct about what "seasoned" is. But what does that have to do with me agreeing with the author's article in JavaWorld and asking what others thought?

Moving along...


That's the definition of "seasoned": one with a lot of experience. How do you get experience? Consistent effort over time.


I get experience by hanging around people who know more than I do on the topic-at-hand, and ask them what they think!


Debbie

[ UD: edited ]

Debbie Dawson
Ranch Hand

Joined: Aug 31, 2010
Posts: 30
Jimmy Clark wrote:Debbie, the JavaBean get/set method style was created for simple "data" classes. It should not be applied to complex classes that contain processing algorithms or any type of behavior/functionality.


Okay.


Debbie
Debbie Dawson
Ranch Hand

Joined: Aug 31, 2010
Posts: 30
David Newton wrote:
Jimmy Clark wrote:Debbie, the JavaBean get/set method style was created for simple "data" classes.

That's not really true; JavaBeans were created to allow tooling and other beans to use and manipulate objects, and to foster application composition. The relative simplicity or complexity of the components was never a consideration--this was one of the selling points of JavaBeans: a complex application or component could be manipulated and plugged in the same way as a simple one.

http://www.oracle.com/technetwork/java/javase/tech/index-jsp-138795.html


Okay again!


Debbie

Debbie Dawson
Ranch Hand

Joined: Aug 31, 2010
Posts: 30
Debbie Dawson wrote:Why might Getters/Setters be bad in my own words?

Hmmm...

I think the main thing is that you are *supposedly* supposed to keep "data" and "behavior" close together. Well designed classes have the "right data" and the "right actions" in the same class. If you have a class "Order", you would ideally not only have a properties called "subTotal" and "salesTaxRate" but a method called "calculateSalesTax()" and "calculateOrderTotal()".

You would want to avoid having and using "getSubTotal()", "getSalesTaxRate()", then reading said values into another space (be it a class or wide-open-range), calculating the "orderTotal" and then using "setOrderTotal()" back in the original "Order" class. (Such a scenario is how we used to do things in BASIC!!)

I think that is the #1 scenario that I took from the article and comments I've seen online.

Does that mean that you never need to Get/Set properties in an object? No. But I think the author's points were:
1.) Keep "data" and "actions" as close together as possible (read "encapsulation")
2.) When an Object cannot complete something on its own, pass the ENTIRE OBJECT to an Object that can, versus cherry-picking Attributes and treating them like global variables.

If you have coffee (Attribute) in a Cup (Object), and you want to warm up your coffee, you do not pour the coffee (get) into your hands (rebel environment) and put it in the microwave (another Object) and then when it is warm transfer it back (set) to your Cup?! "In the real world" you would simply take the coffee (Attribute) in the Cup (Object) and place it in the Microwave (another Object) so that you can Warm Up (Microwave Method) Coffee (Cup Attribue) in your Cup (Object), right?!


Anyone care to comment of my comments?



Debbie


Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42648
    
  65
I have edited the conversation to try to get it back on topic. Please remember that "Be Nice" is the cardinal rule of this site.


Ping & DNS - my free Android networking tools app
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: About Getters & Setters