Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

set Object direct or indirect?

 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is better:

to provide a method void which sets the properties of the object:


or to have a return type and set the value explicitly:



What is better? Why?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Neither one makes much sense to me, especially the method "getProps()" in the first version which in fact doesn't "get" anything. A method named "getX" should always return X.

What's wrong with the simpler, more obvious



or even better, giving the class a constructor?

 
Steve Luke
Bartender
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This isn't a direct answer to your question, I don't think, but it is important.

1) a getXXX method should return something. It is a standard naming convention, and should be followed.
2) The value that a getXXX method returns should be related to what the method name is. For example, a method called getProps() should return a value that represents the 'Properties' of the Object it is being called on (maye a Properties object, or a Map of name-value pairs, or event a List of properties).

Your method seems to be 'setting up' or 'filling' the properties of the passed in Object, not returning them, so using getXXX is probably not a good idea. I would suggest using an alternate name, like:

Or, assuming that MyObject type is used to represent the properties you are 'getting', you could have the 'getProps' method create and return the MyObject object:

Again, standard get methods usually don't have parameter methods, but it isn't abnormal to have them. So you might do something like this:


The important part with the get method is that there is return value, and that the return value has a relationship to the work the method is doing. So I wouldn't consider filling MyObject with properties and returning some other view or some single Property from inside MyObject as being good practice.

If setting up the OtherObject is complex and you feel it should be done in a different method, feel free to do so, but it would be easier to understand if it went one of these two ways:

Or
 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you to both, that helped me much!!

This is exactly what I was doing:





The naming convention get/set...Now, it s clear, thank you!

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic