Getters and Setters in Java convention [duplicate]

戏子无情 提交于 2019-12-30 09:57:24

问题


My Java is a bit rusty (been doing C# for the last couple of years). Also I hope this won't be a very subjective question.

Anyway say I had class Person (yeah a bit of a cliche, I know), with no behaviour (C# version):

public class Person 
{
   public string Name { get; set; }
   public int Age { get; set; }
   // say 10+ properties
}

How would the equivalent Java version look like ? I know I can write bunch of getters and setters (but say I had 10+ properties), it feels like a lot of boilerplate. Is it considered bad practice to just do:

public class Person {
   public String name;
   public int age;
   // rest of the stuff here
}

I feel a bit uneasy about this. I realise there is no "right answer" but, I'm more interested in the general conventions and best practices.


回答1:


You should write getters and setters. Or better - let your IDE generate them automatically. Otherwise you break the encapsulation. Also maybe you need just a getter.

Another advantage of using a getter or setter can be doing some checks or preprocessing before returning or setting the field.

Here is a sample code snippet:

private String name;

public String getName() {
   return this.name;
}

public void setName(String name) {
   this.name = name;
}

Optionally you can use http://projectlombok.org/ and write it like this using annotations:

@Getter @Setter
private String name;

The code generation is done compile time.




回答2:


It's better to have getter/setters to return the fields so that you can encapsulate the way the fields are calculated. Although it happens rarely, there may come a time when you want to change something like this:

getBalance()
{
   return this.staticBalance;
}

to this:

getBalance()
{
  return calculateBalance();
}

And the only way in Java to change field behavior without potentially changing tons of code (or worse requiring your API users to change bunches of code) is to use getters and setters.

Other benefits are:

  • Ability for subclasses to override the behavior
  • Improved thread safety because you can synchronize access

Writing the boilerplate is tedious, but a good IDE will just generate those methods for you from the field names.




回答3:


You have to create manual functions to do it.

So first, you create a backing field.

private String _backingString

Then you create getters and mutators

public String getBackingString()
{
  return this._backingString;
}

public String setBackingString(String value)
{
   this._backingString = value;
}

It's the Java convention - there's no other way around it. However, you'll be pleased to know most IDEs have tools to generate these. Just google around for your favourite IDEs generator tool.

You can see this SO question on how to do this in Eclipse.




回答4:


You should do getters and setters for each. Modern IDE's make it easy because they have auto-insert option. Eventually you can create get and set methods in Calendar's class style.




回答5:


I often use both approaches, having getters and setters and not. I always use private fields which force the use of getters and setters in my model. Using JPA and Hibernate my model is tied to my DB schema. Then for my DTOs which are normally used for things like RESTful services I use mostly public fields with no getters and setters. These DTOs have no logic and get marshaled out to JSON or created from JSON that's being set from a client so I find no need for the getters and setters. I usually don't end up override equals and hashCode for these too. They are as simple as possible.

So I don't think there's a right or wrong way and it depends on usage.

And if you are going to create you getters and setters let your IDE do the work for you.




回答6:


Which IDE are you using? In Eclipse you can create them automatically from the source menu, and their names are derived from the field names. Code:

private String myField; 
public String getMyField()
{
   return this.myField;
}
public void setMyField(String value)
{
   //validation stuff
   this.myField = value;
}


来源:https://stackoverflow.com/questions/18046071/getters-and-setters-in-java-convention

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!