jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes set Object direct or indirect? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "set Object direct or indirect?" Watch "set Object direct or indirect?" New topic

set Object direct or indirect?

nimo frey
Ranch Hand

Joined: Jun 28, 2008
Posts: 580
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

Joined: Jul 08, 2003
Posts: 24199

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?

[Jess in Action][AskingGoodQuestions]
Steve Luke

Joined: Jan 28, 2003
Posts: 4181

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:


nimo frey
Ranch Hand

Joined: Jun 28, 2008
Posts: 580
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!

I agree. Here's the link: http://aspose.com/file-tools
subject: set Object direct or indirect?
jQuery in Action, 3rd edition