Java约定中的Getters和Setter [英] Getters and Setters in Java convention

查看:140
本文介绍了Java约定中的Getters和Setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Java有点生疏(过去几年一直在做C#)。我也希望这不是一个非常主观的问题。

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.

无论如何说我有班级(是啊有点陈词滥调,我知道),没有任何行为(C#版本):

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
}

等价的Java怎么样?版本看起来像?
我知道我可以写一堆getter和setter(但是说我有10多个属性),感觉就像很多样板。
仅仅这样做是不好的做法:

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.

推荐答案

你应该写getter和setter。或者更好 - 让IDE自动生成它们。否则你打破了封装。也许你只需要一个吸气剂。

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.

使用getter或setter的另一个好处是可以在返回或设置字段之前进行一些检查或预处理。

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

以下是示例代码段:

private String name;

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

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

您可以选择使用 http://projectlombok.org/ 并使用注释这样写:

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.

这篇关于Java约定中的Getters和Setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆