Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getters and Setters in Java convention [duplicate]

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.

like image 736
Dimitar Dimitrov Avatar asked Dec 01 '22 03:12

Dimitar Dimitrov


2 Answers

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.

like image 143
Petar Minchev Avatar answered Dec 02 '22 16:12

Petar Minchev


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.

like image 43
lreeder Avatar answered Dec 02 '22 16:12

lreeder