Search code examples
javaconventions

Getters and Setters in Java convention


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.


Solution

  • 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.