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.
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.
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:
Writing the boilerplate is tedious, but a good IDE will just generate those methods for you from the field names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With