I'm creating a data transfer object and can't decide whether it would be better to just give public access to the instance variables or if there would be a purpose to using getters and setters to access the data?
According to the Data transfer object Wikipedia Article:
A DTO does not have any behavior except for storage and retrieval of its own data (accessors and mutators). DTOs are simple objects that should not contain any business logic that would require testing.
It seems that public access would be justified for a DTO's instance variables.
Here is the example I'm working on:
Ivars with public access modifier:
class ServerContext
{
public String host;
public String user;
public String password;
public int port;
ServerContext(String host, String user, String password, int port) {
this.host = host;
this.user = user;
this.password = password;
this.port = port;
}
}
vs. private access modifiers:
class ServerContext
{
private String host;
private String user;
private String password;
private int port;
ServerContext(String host, String user, String password, int port) {
setHost(host);
setUser(user);
setPassword(password);
setPort(port);
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
EDIT: Could these be valid arguments for keeping the ivars private:
The potential of refactoring a DTO later to have more functionality?
Wanting to keep implementation consistent between DTO and regular objects?
ServerConfigurationData
orServerContext
.