While reading some tutorials, I see that they specify that the getter and setter methods should be public.
That is often done in tutorials because it's easier to write, while also providing "some kind of object oriented feeling", because you still have some control using getters and setters.
You could (not recommended) also use public fields and omit the setters and getters completely:
public class Foo {
public int i;
public String s;
}
But when using setters instead you can for example validate the data:
public class Foo {
public void set(int temperature) {
if(temperature < 273) throw new IllegalArgumentException();
this.temperature = temperature;
}
}
But what if you need to validate multiple values at once? Using a setter you can only always validate the current value, but you can't validate multiple setter calls together. That's one scenario where public setters are bad.
The other thing is: Object oriented programming is much about telling names: setXYZ
doesn't you tell much. For example setTemperature
might be fine for a thermostat. But that's it. Maybe you even got something more advanced: setTemperatureLevel
(values 1-5) which then sets the internal desiredTemperature
and when this value is higher than the current temperature you want to set heater
to true
.
When using simple setters, you have no control if all those steps are done in the right order, or if maybe some step was skipped. But using a setLevel
method that does all of that inside the class, there's no way to screw up for the method caller.
But of course there are places in the Java world where those public setters and getters are quite handy: In a lot of frameworks, like something for mapping database to DAOs, or DTOs for JSON de/serialization, it makes things easier. Because here it's used as a convention for reading and writing the fields of an object. Those objects are often referred to as JavaBeans.
But when it comes to your domain objects, I highly recommend to keep everything private you don't want others to access and/or manipulate.