Java – good practice for editing objects by reference?
•
Java
Suppose I have a type called superstar Now I want to have a method to do some work and edit some properties of a superstar object
There are two ways to do this Mode 1 will be as follows:
private Superstar editSuperstar(Superstar superstar){ .... superstar.setEdited(true); return superstar; } ... superstar = editSuperstar(superstar);
Mode 2 will be like this:
private void editSuperstar(Superstar superstar){ .... superstar.setEdited(true); } ... editSuperstar(superstar);
Which of these two possible approaches is considered a "best practice"? The first or the second pseudo "by reference"?
Solution
In your case, the second form is the favorite because you directly change the attributes of one of your superstars (editing) However, if you have a way to use a superstar object and return an updated version of it (without changing the original object), the first form will help me
Finally, since both examples use only superstar objects, they should be member methods of the superstar class
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码