• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

setter / getter: doesnt make sense

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi there,

I've come to the point where, in the 2 books I am using right now, the authors are mentioning the getters and setters as a way to "enforce" control over the variables. It doesnt quite make sense to me... the couple of examples I foudn online do not make much sense either...

can someone shed some light on this for me please?

basically: why would I NOT want to interact directly with the variables I have created in a class? it seesm more "natural" to me to use them directly...

and : is the use of constructors and getters/setters mutually exclusive? (it seems quite difficult to me to combine both at the same time even though the purpose is different)

thanks!
 
best scout
Posts: 1294
Scala IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi choubix,

basically there's nothing wrong with accessing public variables directly - as long as you only set and get values! If you need to do slightly more than just that or for example if you need synchronization for multithreaded apps you will have to use getter/setter methods. Another example are immutable data. If you directly access mutable member variables like a Date or any mutable collection you break encapsulation because all clients which hold a reference to it can manipulate the internal state of your object from outside the object.

In Java there's of course something special about getters/setters. It's part of the JavaBeans convention and used by many tools and frameworks to automatically identify properties of a class.

and : is the use of constructors and getters/setters mutually exclusive? (it seems quite difficult to me to combine both at the same time even though the purpose is different)


I'd say it's not mutually exclusive. But often you don't have all information available when you create an object so that you could pass in all needed values. And if you have more than a few members you want to set the signature of your constructors soon get very ugly. But it is always a trade-off to decide what to set in a constructor and what not.

Marco
 
Greenhorn
Posts: 14
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you have a public int instance variable "age" there's nothing to prevent someone or some other method in your application from setting the employee's age to 325 years old or to a negative value. With the use of a setter method you can build-in or enforce a restriction to reasonable values. The point is to make those instance variables private and give access only through the public (or protected or default) getter and setter methods. The getter method then, is necessary for one thing because the instance variable has been made private. Hope this helps.
 
Ranch Hand
Posts: 710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The use of getters/setters is part of OO design. By having a setter/getter, you can set your instance variables to private, giving you more control over what the variables are set to. For instance, say you have an object Cat with a numberLegs variable. You wouldn't want someone to be able to say your Cat has -2 legs (if you have a picture of a cat with -2 legs, I would love to see it!). By requiring all calling code to use the setter, you can put a requirement that the numberLegs be greater than or equal to zero.

In summary, they allow you to have control over what values can be used in your instance variables, which can help prevent your program from crashing.


Constructors and getter/setters are not mutually exclusive. A constructor is used to perform anything that needs to be done each time an object of a specific type is created, which could be setting the default values of the instance variables. For my Cat example, my constructor would default numberLegs to 4, since that is a reasonably safe value to assign to that variable. I would then have a getter so other programs could pull that variable's value, and a setter in case the particular cat they are dealing with has more/less than 4 legs.
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't think books ever do a good job of explaining this.

Remember that in the 'real world', your often working on a team with dozens of developers. Each may have an idea how something should be used. Using getters and setters keeps people from clobering each other.

Suppose we have an object that stores the age of something as an int. I may need the age stored in years. You may need it stored in minutes. If everyone has direct access to the variables, you never know how anybody will store stuff.

If there are setters, I can enforce the age being in years. If you try and set the age in seconds, the code can reject an age of 525,600 minutes for a person. Even better, you could have a setAgeInMinutes() and a setAgeInYears() methods, which make it clear what the input should be.

You could do the same with getters - getAgeInMinutes() and getAgeInYears(). It doesn't matter how the data is stored internally, and it can be changed whenever the owner of that code wants - as long as she updates the getters and setters correctly, how the data is stored internally doesn't matter. She could even change it to storing it as a date.
 
choubix alex
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi!


Fred, Joe, Mark, Marco: thank you so much for spending of your time writing detailed answers.
I don't know yet if I'll be using multithreading (beginner with only 3 days of Java under my belt! ;) )
maybe it will be useful for what I intend to do but I have not yet reached that stage hehehe ;)

I dont foresen the company hiring programmers in the short term but I understand your point with the setters/getters.
Controlling the data stored in the variables is crucial (it can be quite messy if the code is not explicit! it's already quite difficult after a few days away from the office and when the code is not commented properly...) and can prevent users from storing something that shouldnt be there.
 
Marco Ehrentreich
best scout
Posts: 1294
Scala IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No Problem

As you are new to Java, I would recommend not worry too much about more advanced topics like multithreading. But all the other points here are definitely true and you should think about them right from the beginning. Btw. it's not too much additional work to create getters and setters for some members. I think, today any modern Java IDE has some features to auto-generate such code fragments for the members you wish.

it can be quite messy if the code is not explicit! it's already quite difficult after a few days away from the office and when the code is not commented properly


Good point! A lot of people don't even think about this problem. As the examples above show it's often a good idea to use more reasonable names for getters/setters (basically for all identifiers). This saves you the time for lengthy comments and doesn't become outdated.

Marco
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
At some point later in your Java-life, you might want to think about wether using getters and setters is actually an "Object-Oriented" thing to do.
 
choubix alex
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
well, right now I am at the "embryonic stage" hahaha ;)

but you are right: I've read that the use of Setters/Getters is not fully "OO" compliant. Nevertheless I am really trying to get things to work at the moment.

next on my list is to :
- have a clear roadmap of what I want to develop in terms of functionalities and look/feel (java, swing + webstart / JavaFX)
- get hold of JDBC

Then I will certainly have to design an "infrastructure" for what I want to achieve and finally work on the performance and scalability of the application
(I suppose that means using: Maven 2, Subversion, Hudson, Jira -as hopefully I'll get someone on board late next year and that implementing all these tools would help working with someone else!)

And I am not mentioning the various packages that I will undoubtedly stumble upon when looking for reporting capabilities, charting etcetc...









 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic