• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Is it advisable to use getters and setters in Java?

 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is it advisable to use getters and setters in Java, or is this just a waste of time? Some developers seem to be against their use.
 
Saloon Keeper
Posts: 13265
292
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, always hide your fields.* You never know if you might want to change the internal representation of your type, and if you expose your fields by making them non-private, you're stuck with them forever.

A possible exception to this rule are types that serve no other purpose than to represent data that needs to be serialized, such as a class that represents an XML element. Seeing as their internals are pretty much already exposed when you serialize them, using getters usually only adds a lot of unnecessary boilerplate. Even then, I often prefer to err on the side of safety and use getters instead of public fields anyway.

*Note that I said "hide your fields" and not "yes, always add getters and setters". Don't blindly add getters for every field that your class consists of, only those that actually need to be exposed. Be even more judicious with setters. Most classes don't need setters at all.
 
Saloon Keeper
Posts: 1282
40
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Something I never used to see but I see fairly often now are classes with getters and setters for everything, but in order of "What the hey?" No .hashCode() override, no .toString(), no .equals() and no constructor!

I can't speak for everyone, but when I see something with no constructor, no .equals() and a bunch of getters and setters it indeed makes me ask "What style of coding is this??"

I feel like re-iterating, I'm seeing this more and more.  What gives?

Otherwise, I completely agree with Stephan's points.

 
Master Rancher
Posts: 4027
53
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:A possible exception to this rule are types that serve no other purpose than to represent data that needs to be serialized, such as a class that represents an XML element


Antonio - another good exception that overlaps with this is a record class, which is a new feature introduced in Java 16 (earlier as a "preview" feature).  Record classes are very quick and easy to declare - that's the point.

With this, you get an immutable class with two fields, and a constructor you can use to set the fields at the time of creation.

Here you automatically get a "getter" method first(), which doesn't use the word "get", but accesses the field just as you would expect if you'd written a getFirst() method. Also, just for Jesse , you get fully implemented toString(), hashCode() and equals() methods.
 
Saloon Keeper
Posts: 24300
167
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:
I can't speak for everyone, but when I see something with no constructor, no .equals() and a bunch of getters and setters it indeed makes me ask "What style of coding is this??"



It's a pure JavaBean. You only need to override toString if you want it to render something displayable instead of the default glop. Not every bean needs that. Likewise, overrides for hashCode() and equals() are essential for ORM objects but not for everything else in the Universe. And not having a constructor is often common as well.

In fact, that pretty much describes the Managed Beans in JavaServer Faces (JSF). They MUST be constructable with no arguments, they NEVER get compared or hashed (not counting the JEE scope dictionaries, which have their own hashing), and JSF will never invoke toString() on them.
 
Marshal
Posts: 74020
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
But would a beginner want to write a JavaBean? An object with straight setters and getters might be all right in a JSF context, where its use can be controlled, but many objects don't necessarily want to have their fields reset by setter methods. I suspect there is a widespread misunderstanding about the use of the beans pattern.
MS shows the record type, which is a welcome pattern. It recognises the usefulness of immutability. The supertype of record types (API link) does seems to specify equals(), hashCode(), and toString() methods.
 
Tim Holloway
Saloon Keeper
Posts: 24300
167
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Records are very new. Traditionally, JavaBeans were the basic building blocks for field-oriented data containers. To the point that originally, Sun had a JavaBean Editor, though that didn't last long.

I'm not certain that records are fully-interchangeable with legacy JavaBeans. Depending on how interchangeable they are, however, I'd expect them to be supported in systems like JPA and, yes, JSF, Both of which are originally designed around JavaBeans/POJOs, as are many other mission-critical subsystems. Doubtless, should records prove useful in such environments, they will eventually gain native support in the Jakarta/JEE standards and elsewhere.
 
Campbell Ritchie
Marshal
Posts: 74020
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tim Holloway wrote:. . . I'm not certain that records are fully-interchangeable with legacy JavaBeans. . . .

At present, I think that is unlikely. A record doesn't usually have a no‑args constructor, nor does it have the annotation seen in this Color constructor.

[additional]Nor do the getters in a record match the naming convention for Beans.
 
Tim Holloway
Saloon Keeper
Posts: 24300
167
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:[additional]Nor do the getters in a record match the naming convention for Beans.


Shows how long my memory runs. Not even 3 messages up.

However, a lot of services (especially JEE services) use Apache BeanUtils as their introspection and access mechanisms. I'd imagine that popping record support in there might light up a lot of systems all at once.
 
Campbell Ritchie
Marshal
Posts: 74020
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tim Holloway wrote:. . . popping record support in there might light up a lot of systems all at once.

That sounds like a good idea. That would obviate one of the potential problems with Beans, the many setXXX() methods.
 
Antonio Moretti
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:Yes, always hide your fields.* You never know if you might want to change the internal representation of your type, and if you expose your fields by making them non-private, you're stuck with them forever.

A possible exception to this rule are types that serve no other purpose than to represent data that needs to be serialized, such as a class that represents an XML element. Seeing as their internals are pretty much already exposed when you serialize them, using getters usually only adds a lot of unnecessary boilerplate. Even then, I often prefer to err on the side of safety and use getters instead of public fields anyway.

*Note that I said "hide your fields" and not "yes, always add getters and setters". Don't blindly add getters for every field that your class consists of, only those that actually need to be exposed. Be even more judicious with setters. Most classes don't need setters at all.



Thanks. This made sense to me. I was lost on some of the other comments!!
 
Antonio Moretti
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:Yes, always hide your fields.* You never know if you might want to change the internal representation of your type, and if you expose your fields by making them non-private, you're stuck with them forever.

A possible exception to this rule are types that serve no other purpose than to represent data that needs to be serialized, such as a class that represents an XML element. Seeing as their internals are pretty much already exposed when you serialize them, using getters usually only adds a lot of unnecessary boilerplate. Even then, I often prefer to err on the side of safety and use getters instead of public fields anyway.

*Note that I said "hide your fields" and not "yes, always add getters and setters". Don't blindly add getters for every field that your class consists of, only those that actually need to be exposed. Be even more judicious with setters. Most classes don't need setters at all.



I thought I had this, but now I still have some problem seeing the point of making a field private, then making a getter and a setter for it. For example, suppose we have code to draw a rectangle:



Here if we make the fields private and then write this:



Then you are still stuck with width and height variables in the fields, and in the getters and setters. We just put a function in front of them and now we have a lot of extra lines of code. I cannot see the point of doing this.
 
Campbell Ritchie
Marshal
Posts: 74020
332
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your setter methods are not written correctly; they should validate their arguments and only accept positive arguments. Even if you correct that, your public fields permit this sort of horror:-Using public fields can make it impossible to change the implementation later on.
 
Stephan van Hulst
Saloon Keeper
Posts: 13265
292
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The point is that if you ever want to ensure that a rectangle can't have a negative width or height, you can add code to your constructor or setters that checks the parameters and throws an exception if the argument is invalid.

Another point is that mutable classes are the cause of many bugs. Immutable classes are much easier to work with. You really don't need setters that often I a well designed application. Why would you want to change the dimensions of an existing rectangle?

You need fields to be private to enjoy these benefits. And if you have a REALLY good reason to make your fields non-private, you can always do so later. But once a field is public and the code had been released, you can never go back.
 
Antonio Moretti
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks.

So just to summarise, the main purpose of using setters is for the validation of values. However, by making the fields private we also need getter so we can read them if needed. Is this correct?
 
Stephan van Hulst
Saloon Keeper
Posts: 13265
292
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Antonio Moretti wrote:the main purpose of using setters is for the validation of values.


No, the main purpose of setters is to allow the outside world to change a property of an object. Validation is secondary: You validate because you wrote a setter. You don't write a setter because you want to validate.

Regardless of whether you want to add validation or not, keeping fields private is a good idea anyway. The reason for this is that you give up many benefits when you make a field non-private, of which being able to perform validation is only one. A more important reason is immutability. It doesn't make sense to change the dimensions of a rectangle after you've created one. If you don't keep your fields private, you can't guarantee that your objects won't suddenly change when you don't expect them to.

However, by making the fields private we also need getter so we can read them if needed. Is this correct?


Yes, getters are there to expose a property to the outside world.
 
Jesse Silverman
Saloon Keeper
Posts: 1282
40
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You could also find that you want to re-factor your object so that one of your data members disappears completely.
The public getter might stay just exactly as it is to the user, but now will be computing that quantity on the fly, or getting it from somewhere else, without disturbing any user code.

If you had exposed that same data member directly, you would be painted into a corner, because there would be no way to find and fix all the callers, which might not even be under your control at all.

One of the biggest changes in Java style has been appreciating the many benefits of immutability.
I had the old feelings for a long time "But it is my data, I want to change it whenever I feel like!"
Aside from being able to share it amongst threads or amongst different callers without making lots of otherwise unnecessary protective copies, an immutable value can be safely used as a key in a Map or a member of a Set.
If you use a mutable object there you can easily accidentally cause your Set or Map to act like you are on Crazy Pills.
 
Tim Holloway
Saloon Keeper
Posts: 24300
167
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is much wisdom that has been presented here, and I hope it's becoming plain why setters and getters are so popular.

One thing I'd add is that sometimes the field datatype changes and in order to avoid breaking existing code, overloaded accor methods can present the old datatypes (with possible caveats). I've done a lot of that, which is what turned me off Hungarian Notation so many years ago.

Finally, some IDEs do have "wizards" that can automatically generate set/get methods without having to tediously hand-code them all!
 
Antonio Moretti
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesse Silverman wrote:You could also find that you want to re-factor your object so that one of your data members disappears completely.
The public getter might stay just exactly as it is to the user, but now will be computing that quantity on the fly, or getting it from somewhere else, without disturbing any user code.



But then would it be right to still call such a getter a getter, since it is no longer getting the value of a field, but computing one?
 
Antonio Moretti
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:

Antonio Moretti wrote:the main purpose of using setters is for the validation of values.


No, the main purpose of setters is to allow the outside world to change a property of an object. Validation is secondary: You validate because you wrote a setter. You don't write a setter because you want to validate.



Now confused again. The only reason I have been shown for using a setter was to validate, so we cannot do like rect.height = -1 etc. This I understand. Now you say I validate because I have a setter? Could you give me an example using  setter that is not validation?
 
Mike Simmons
Master Rancher
Posts: 4027
53
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think Antonio is referring to, why use setters rather than making the field public?  The goal of allowing the outside world to change a property can be accomplished by a public mutable field, or setters.  So his focus is on what differentiates those two approaches.

My reasons for using a setter as opposed to a public mutable field:
  • Validation
  • Allow future changes of data type without requiring changes in outside code
  • Logging
  • Debugging
  • Avoiding arguments with the majority of Java / OO community

  • The logging and debugging points are similar - if you need to investigate how or when a particular value got set, you have one point in your code that you can log the value, or set a breakpoint in your debugger, to see what's going on.  If you don't have this, you may have many points of contact to log or set breakpoints.

    Even if you don't anticipate the need for most or any of these, it's nice to know that if you need it later, it's easy to add this sort of functionality.  If you let other code access your fields directly, then it can be much harder to change later.
     
    Tim Holloway
    Saloon Keeper
    Posts: 24300
    167
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    The only thing a setter has to do is "set". Anything else is gravy. More of my JavaBeans don't validate on set methods than do.

    And in fact, occasionally I'll remove a property and keep the set method. having it do nothing at all, just to avoid breaking the calling code.
     
    Tim Holloway
    Saloon Keeper
    Posts: 24300
    167
    Android Eclipse IDE Tomcat Server Redhat Java Linux
    • Likes 2
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Adding to Mike's comment on debugging, you can often set breakpoints on variables directly, but the overhead is typically much higher than setting a breakpoint on a method (such as a setter). So debugging can go faster if you use setters.
     
    Antonio Moretti
    Ranch Hand
    Posts: 56
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    One last comment while on this subject.

    Why not, in my example, just use a setter like setSize(int w, int h) { //blah}, and kill two bird with one stone?
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 13265
    292
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Well, what if I only want to change the width, and not the height? Should I really have to look up the current height and pass it back into the setter, just to ensure it doesn't change?
     
    Jesse Silverman
    Saloon Keeper
    Posts: 1282
    40
    Eclipse IDE Postgres Database C++ Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Antonio Moretti wrote:
    But then would it be right to still call such a getter a getter, since it is no longer getting the value of a field, but computing one?



    It depends on the context, C# for instance has Properties, and all of its own terminology around that approach, which keeps coming to mind, not repeating it here because "Java".

    EJB, I am not sure.  In generic OOPS (whatever THAT is), a nicely encapsulated attribute might over a period of time go from being real, to being virtual/computed, to someday being real again, all without disturbing the code of those using the class.
    And that is a huge advantage.
     
    Saloon Keeper
    Posts: 8579
    71
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Immutable classes and Getters:

    IF a class is immutable and contains a field that is mutable THEN you don't want to pass a reference to that field back out of the class object using a getter because it could then be modified thereby violating its immutability. In such cases you would most likely want the getter to return a copy of the field. This is just an example but there are others, returning Lists comes to mind as well.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 13265
    292
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    If you don't like calling them "getters", call them "accessors" instead. But "getters" is fine.

    A getter gets a property of an object. It doesn't matter whether that property comes from a field or is computed. Whether it's computed or not is an implementation detail and should not be visible to the caller of the getter.

    This also means that getters should always return quickly! A computed property must be a simple calculation, and may not access external resources such as databases.

    Methods that block or take a long time to return should either be named differently using prefixes such as "find", "load", "compute", or they should be members of a class that is obviously responsible for accessing the resource.
     
    Antonio Moretti
    Ranch Hand
    Posts: 56
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Stephan van Hulst wrote:Well, what if I only want to change the width, and not the height? Should I really have to look up the current height and pass it back into the setter, just to ensure it doesn't change?



    I was thinking, with setSize(), you no longer refer to the fields by name. There is no hint of width and height. So you couldm, in future, change the fields completely. For example, if this was a point, and method was setPosition(), you could change the fields from cartisan (x, y) to polar coodinates (angle, distance) one day and everything would still work. But is that a setter? It just seems to me that having a setter like setWidth() that does nothing other than set the value of a private field (and potentially validate) is questionable.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 13265
    292
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Antonio Moretti wrote:I was thinking, with setSize(), you no longer refer to the fields by name.


    Why is that important? The caller doesn't know that there are fields with names width and height. The fact that we have an accessor getHeight() is not an admission that it the class also uses a backing field with the name height. Why should we make extra effort to use different property names for our accessors than for our backing fields?

    Even if the class used a backing field of a compound type that expresses the entire size of the rectangle, we could still add a setter that only modifies the horizontal component of the size. This can be handy if you don't want to modify the vertical component. But please note that an object should generally not be modifiable at all!

    For example, if this was a point, and method was setPosition(), you could change the fields from cartisan (x, y) to polar coodinates (angle, distance) one day and everything would still work.


    And if you have accessors or mutators for x and y separately, how does that prevent you from changing the backing fields to polar coordinates?


    It just seems to me that having a setter like setWidth() that does nothing other than set the value of a private field (and potentially validate) is questionable.


    Please explain in your own words why you find it questionable. Keep in mind that we already explained to you why it's a bad idea to make a field non-private. Setters are then your only recourse.
     
    Campbell Ritchie
    Marshal
    Posts: 74020
    332
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Carey Brown wrote:. . . return a copy of the field.

    There is a whole section in Effective Java by Joshua Bloch about that; he calls it, “taking a defensive copy.”

    . . . returning Lists comes to mind as well.

    There are at least five different ways you can return a List, four of which behave as a sort of defensive copy. I think the same applies to sets and maps.
     
    Antonio Moretti
    Ranch Hand
    Posts: 56
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Stephan van Hulst wrote:

    Antonio Moretti wrote:I was thinking, with setSize(), you no longer refer to the fields by name.


    Why is that important? The caller doesn't know that there are fields with names width and height. The fact that we have an accessor getHeight() is not an admission that it the class also uses a backing field with the name height. Why should we make extra effort to use different property names for our accessors than for our backing fields?



    Thanks for you help. I will study your answer carefully, but just to reply quickly to the above, we have been taught to name setters and getters after the field names. This is also what IDEs like Netbeans do, if you let them generate the getters and setters automatically, it always bases them on the field names. For these reasons, I assumed that getters and setters must be named after fields, otherwise, they are not strictly getters and setters, but methods that do something slightly different.
     
    Campbell Ritchie
    Marshal
    Posts: 74020
    332
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Stephan van Hulst wrote:. . . an object should generally not be modifiable at all! . . .

    That is an understanding I suspect takes a long time to filter down to learners.
  • 1: It takes time to filter down to their teachers, and learners won't learn what their teachers don't know.
  • 2: It is necessary to learn mutable objects as well as immutable, so learners may not grasp the advantages of immutability.
  • Even if you do have an object whose state you want to alter, setXXX() methods are probably not a good way to do it. Example: you might have a kettle, and you might mimic it with a Kettle object. You probably won't want a setTemperature() method, but methods like these:-I wouldn't write a setTemperature() method, nor would I write a setBalance() method in a BankAccount class; I would use deposit() and withdraw() or similar. Both those examples much better reflect what happens in real life.
     
    Campbell Ritchie
    Marshal
    Posts: 74020
    332
    • Likes 2
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Antonio Moretti wrote:. . . we have been taught to name setters and getters after the field names. This is also what IDEs like Netbeans do, if you let them generate the getters and setters automatically . . .

    Look up “bean pattern”. The bean pattern is useful in very specific circumstances, and that mandates getXXX() and setXXX() methods called after the fields. The bean pattern is useful for recording the state of GUI components, and a few other instances (we discussed it in the last week in JSF (=Java Server Faces, I think). but it is probably not suitable for general use. Look at my example of honey, where there are two possible implementations each returning the percentage of sugar in the honey. It would probably be more accurate to say that honey contains 3% of “something else”, but I am trying to teach programming not apiculture.

    [addition]If In had used the bean pattern for the Honey class, that might have fixed the implementation or at least made it more difficult to change the implementation.
     
    Antonio Moretti
    Ranch Hand
    Posts: 56
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Thanks. The honey example made it makes sense to me. The problem was the way we had been taught.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 13265
    292
    • Likes 2
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Antonio Moretti wrote:we have been taught to name setters and getters after the field names. This is also what IDEs like Netbeans do, if you let them generate the getters and setters automatically, it always bases them on the field names. For these reasons, I assumed that getters and setters must be named after fields, otherwise, they are not strictly getters and setters, but methods that do something slightly different.


    An IDE is a tool that helps a developer perform actions more quickly and easily, but in the end it's still the developer's own responsibility to design the application.

    While using the same name for accessors and for backing fields is very common, making a hard rule out of it is pointless and even leads to problems where beginning programmers habitually create accessors that they don't need.

    Here's the best advice I can give: In your mind, separate the abstract concept "property" from the concrete "field". As we've seen before, a point in a Cartesian plane has an abstract property "angle between the horizontal axis of the plane and the polar axis between the point and the polar origin". If your application needs to access this abstract property and use it outside of the Position class, you can add a getter angle() or getAngle() for this abstract property.

    Implementing your abstract properties comes later. If you can implement an abstract property very easily and efficiently by adding a field of the same name, then great! If you need to calculate it from other properties, then that is fine too. The important thing is that you write getters for abstract properties, and not because you want to access a field, because fields are implementation details and not interesting to outside code.
     
    Antonio Moretti
    Ranch Hand
    Posts: 56
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Stephan van Hulst wrote:...If you need to calculate it from other properties, then that is fine too.



    Thanks Stephan. Your last post was a great help. Just to refer to that quote up there, that threw me a little. What did you mean by calculate if from other properties? Did you mean that, or did you mean fields?
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 13265
    292
    • Likes 2
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I meant properties, but that is not to say you can't directly refer to fields that implement those properties. A computed property isn't necessarily calculated from fields directly. You can also call methods that represent other properties than those implemented by fields:

    The "game over" property of a game of Tic Tac Toe could have been implemented by returning a boolean field isGameOver that is updated when the game is over, or it can be calculated on the fly. When calculating it on the fly, it may refer to other properties (such as the "winner" property) or it may refer to fields directly (such as the board field).

    The "is draw" property is computed without referring to any fields directly.
     
    Jesse Silverman
    Saloon Keeper
    Posts: 1282
    40
    Eclipse IDE Postgres Database C++ Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Other languages that are rather "Java-like" elevate the concepts of properties to have language support.
    They behave rather like what is being described in this thread and to me feel like a Grey Area between methods and data members.
    Java doesn't have direct language support for Properties with a Capital P, but those working in more than one language will recognize all the patterns of design and behavior either way.
     
    Campbell Ritchie
    Marshal
    Posts: 74020
    332
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Isn't there something similar in JavaFX? Is that FX's greatest achievement?
     
    With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    reply
      Bookmark Topic Watch Topic
    • New Topic