Java Getter и Setters для лучших практик простых свойствJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Гость
 Java Getter и Setters для лучших практик простых свойств

Сообщение Гость »


I know this is a common question and I've read several answers but they're all very subjective and I'm trying to get an answer on best common practice (i.e what to use a majority of the time).
My background is in C# .net and I'm re-writing an application in Java (ver. 21). With C# a public property with a getter and setter is functionally the same thing as a private field with a public getter and setter (C# example below). The get and set are implicitly used when referencing the property. So in practice 99% of the time I use a public property with getter and setter because it gives me the added benefit of encapsulation and doesn't add any verbosity to the code.
Now with Java I'm struggling when to use getters and setters. If I where to code like I do with C#, most of my java object properties would be private fields with public getter and setter methods. That makes the code really verbose (example1 below) and I'm not sure if it's necessary/common for simple objects like json responses (mapped by jackson) or entities.
So with that all being said, in practice what is the most standard way of handling simple properties that just get and set a field in Java (without data manipulation). Like if I where to see an enterprise application what would be the most standard way of handling example1 and example2 below. Based on my research thus far I'm leaning towards example1 (keeps encapsulation), but I don't want to use getters and setters everywhere if it's actually more common practice to just use public fields with simple properties. Дайте мне знать, что вы думаете.
C# get/set:

Код: Выделить всё

namespace SpeedRunAppImport.Model.Entity
{
public class GameEntity
{
public string Name { get; set; }

// Same thing as above
private string _Name;
public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}
}
}
Game Entity:

Код: Выделить всё

@Entity
@Table(name = "tbl_game")
public class Game {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String code;
private String abbreviation;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

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

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getAbbreviation() {
return abbreviation;
}

public void setAbbreviation(String abbreviation) {
this.abbreviation = abbreviation;
}
}
GameResponse (JSON response mapped by Jackson):

Код: Выделить всё

public class GameResponse
{
private String id;
private String name;
private String abbreviation;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

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

public String getAbbreviation() {
return abbreviation;
}

public void setAbbreviation(String abbreviation) {
this.abbreviation = abbreviation;
}
}
Example1 (using getters/setters):

Код: Выделить всё

public void SaveGames(List games)
{
_logger.info("Started SaveGames: {@count}", games.size());

var existingGamesVWs = _gameRepo.GetGamesByCode(games.stream().map(x -> x.getId()).toList());

var gameEntities = games.stream().map(i -> { var game = new Game();
var existingGame = existingGamesVWs.stream().filter(x -> x.code == i.getId()).findFirst().orElse(null);
game.setId(existingGame != null ? existingGame.getId() : null);
game.setName(i.getName());
game.setCode(i.getId());
game.setAbbr(i.getAbbreviation());

return game;
}).toArray(Game[]::new);

_logger.info(Integer.toString(existingGamesVWs.size()));
}
Example2 using fields (assume public fields on objects above):

Код: Выделить всё

public void SaveGames(List games)
{
_logger.info("Started SaveGames: {@count}", games.size());

var existingGamesVWs = _gameRepo.GetGamesByCode(games.stream().map(x -> x.id).toList());

var gameEntities = games.stream().map(i -> { var game = new Game();
var existingGame = existingGamesVWs.stream().filter(x -> x.code == i.id).findFirst().orElse(null);
game.id = existingGame != null ? existingGame.id : null;
game.name = i.name;
game.code = i.id;
game.abbr = i.abbreviation;

return game;
}).toArray(Game[]::new);
}


Источник: https://stackoverflow.com/questions/781 ... t-practice
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»