• 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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

If setter and getter works well for accessing private fields, then why not private methods?

 
Ranch Hand
Posts: 133
1
Eclipse IDE VI Editor Objective C C++ Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
is There any solid reason why? can't we use setters and getters for private methods the same way we use them for private fields ?
 
Saloon Keeper
Posts: 10929
87
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Private methods usually manipulate the state of an object in a way that should be under total control of the object and not publicly accessible. Another reason for private methods is that they are internal helper methods that no one else needs to know about.
 
Swapnil Mishra
Ranch Hand
Posts: 133
1
Eclipse IDE VI Editor Objective C C++ Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
so, can we say a private method is more private and secured than a private field or an attribute?
 
Saloon Keeper
Posts: 28319
210
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
I'm afraid that doesn't translate. "set" and "get" access a class property. They are themselves methods. They manipulate an object's state. A private method is still a method. How do you "set/get" a method? Unless you're working with something like Javascript or Lisp where you can dynamically modify the class instance logic at runtime?

Well, actually there's code reweaving like you get with Aspect-Oriented Programming, but that's not common Java.
 
Sheriff
Posts: 28323
95
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Swapnil Mishra wrote:is There any solid reason why? can't we use setters and getters for private methods the same way we use them for private fields ?


There's something about that question which makes it impossible for me to understand. So let me try to figure out what you are getting at.

You can use a "getter" method to get a particular value from an object, without exposing where that value comes from. Often the value is stored in a (private) field in the object, so like this:
Likewise you can use a "setter" method to assign a particular value in an object; often that means to set the value of a (private) field in the object.

Now, there are other things that "getter" and "setter" methods might do. But typically they are public methods so that instances of other classes can use them.

But there's no reason that you can't have private "getter" and "setter" methods. Although that might seem kind of pointless, the language doesn't forbid that. And somebody might be able to figure out a non-pointless use for them.

Was that your question? Or is your question the thing I can't understand?

 
Carey Brown
Saloon Keeper
Posts: 10929
87
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
An immutable class may have some getters but no setters.
 
Carey Brown
Saloon Keeper
Posts: 10929
87
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Example 1: 'a' is exposed to the world to do whatever it wants with it. Example 2: 'a' is safe guarded and so far only a setter has been provided. Note that if you originally wrote your whole project around the style of Example 1 and then changed to style 2 or 3, all your direct usage of 'a' would need to be updated, in other words, it would not be backwards compatible. Example 3 shows a simple but typical implementation where 'a' is intercepted before its final assignment to 'this.a'.
 
Marshal
Posts: 79956
396
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Your Thread Title wrote:If setter and getter works well for accessing private fields . . .

That is an unwarranted assumption. Lots of people teach that all fields shoud be accompanied by a pair of setXXX() and getXXX() methods, but many of us believe that isn't actually true. If you look up “bean pattern,” you will find that it includes setters and getters, but you will also find that many people don't like the bean pattern; indeed some people call it an antipattern.
Let's have an example where you can have adverse effects from setXXX() and getXXX() methods:-Assuming we don't have any trolley‑buses, electric trains or trams, which use power directly from wires or rails, and no leaks or fuel theft(!), that mimics the real‑life behaviour of vehicles. They lose fuel by travelling and they gain fuel by being filled up (=adding fuel). A fuelContent() or other getter method would be correct; it is equivalent to reading the fuel gauge. But what about a setter method? That could suddenly change the amount of fuel, something that doesn't normally happen.
Similarly, what about a BankAccount class. You would never have a setBalance() method; such changes would only be done via deposit(), withdraw(), or calculateInterest() methods. If you think about it, you will find that getXXX() methods would work well for those classes, but setXXX() methods don't work at all well, and many of us don't write such setXXX() methods.
 
Tim Holloway
Saloon Keeper
Posts: 28319
210
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:That is an unwarranted assumption. Lots of people teach that all fields shoud be accompanied by a pair of setXXX() and getXXX() methods, but many of us believe that isn't actually true.


Emphasis mine.

Before I address the "and", let me discourse on the whole concept of accessor methods. It's worth noting that the Java Persistence Architecture permits field access by either direct access Or get/set, but not both for a given Entity class.

Some people think that get/set is extra coding (true) and inefficient (not with a proper optimising compiler). My IDE has a 1-button solution to the first objection and the second, as noted is moot.

There are significant advantages to accessor methods. For one, they're easier to set debugging breakpoints on (breakpoints on direct variable access tend to really slow things down). For another, they allow for adding validation logic. Finally, some properties cascade where setting one property implies that other properties should track its value. That one is admittedly controversial, though useful.

Some languages have ways to confer those benefits on direct variable access as well, but Java as originally designed wasn't one of them. Again if you're doing Aspect-Oriented Programming (AOP), that's one way of doing things, but it's not the norm (although JPA often uses it). And I think some of the newer record-related functionality leans in that direction, though it's not an area I've studied.

Now as the the "and". Having said all that, as Carey remarked, some class instances are immutable. so "set" methods would be inappropriate. The best they could offer would be an UnimplementedOperationException, and that's not as good as a compile-time error due to the method being undefined altogether. Leave that to subclasses that override read/write functionality The are also, of course, classes where some properties are immutable and some are not. So for these, having a "set", but not a "get" would be the option. I have some of these for things like dropdown menu lists in JSF, since JavaServer Faces works off of the Unified Expression Language (UEL), which in turn, employs get/set to access backing bean properties.
 
Campbell Ritchie
Marshal
Posts: 79956
396
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tim Holloway wrote:. . . the Java Persistence Architecture . . .

Even some of the people who decry Beans as an antipattern will say that persistence is the one thing the Bean Pattern is good for. If you use setXXX() methods for debugging, surely you have them in a protective environment where you can be sure nobody will abuse them. And I said a fuelContent() method would be correct; I fully believe that most getXXX() methods are a Good Thing.

. . . "set" methods would be inappropriate. The best they could offer would be an UnimplementedOperationException, and that's not as good as a compile-time error due to the method being undefined altogether. Leave that to subclasses that override read/write functionality. . . .

Agree. But if you are throwing a new exception from a subtype method, which isn't thrown by its superclass' method, is that consistent with the Liskov Substitution Method?
 
Tim Holloway
Saloon Keeper
Posts: 28319
210
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:Agree. But if you are throwing a new exception from a subtype method, which isn't thrown by its superclass' method, is that consistent with the Liskov Substitution Method?



Actually, what I was referring to was a case where the parent class could set a property but you didn't want the subclass to allow setting the property. In which case, since you cannot erase inherited methods, the alternative is to throw an UnimplementedOperationException.
 
Campbell Ritchie
Marshal
Posts: 79956
396
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There must be a better way to do that than throw an Exception. Even making the subclass' method do nothing at all might be better. Obviously that has to appear in the documentation comments.
 
Tim Holloway
Saloon Keeper
Posts: 28319
210
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:There must be a better way to do that than throw an Exception. Even making the subclass' method do nothing at all might be better. Obviously that has to appear in the documentation comments.


If I do something I'm not supposed to be doing, I want to know about it. If I cannot make the compiler do it, then the next best alternative is to loudly complain at runtime.

Another alternative would be to log the method as an error. But I would only do that if it was better to continue doing wrong than to halt the whole operation.
 
Campbell Ritchie
Marshal
Posts: 79956
396
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Does that mean the subtype IS‑NO‑LONGER‑A supertype? That looks like one of the potential problems with traditional OO programming, which, among other things, has made inheritance so much less popular than twenty years ago.
 
Tim Holloway
Saloon Keeper
Posts: 28319
210
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
I wouldn't go that far. A common case might be where you had a general record type, but wanted classes for specific subtypes of that record. Going back to JPA as an example, recall that all JPA Entity types are required to have a no-argument constructor. However, you can define variant entities over the base record type. I've probably got some code along those lines, but it's not a recent project.
 
You know it is dark times when the trees riot. I think this tiny ad is their leader:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic