Preferred Access Modifier for DTO Instance Variables

design-patternsjavaprogramming practices

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:

  1. The potential of refactoring a DTO later to have more functionality?

  2. Wanting to keep implementation consistent between DTO and regular
    objects?

Best Answer

In layman's words.

Public instance variables violate encapsulation.

In doing so, client code will be coupled to the names of your instance variables.

Client code should not be coupled to anything internal.

Internal things could change in the future.

External interface ( contract ) should not be affected by changed internals.

If you don't want to manually write your getters and setters let the IDE do it for you.

Also, getters and setters lets you use the builder pattern to construct and "build" an instance of your object without the hundred-parameter constructor.

The class having no-behavior doesn't mean you can violate encapsulation. It also doesn't mean it will never have behavior in the future.

Related Topic