Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity objects getters and setters for data properties

I recently started working in Java and was introduced to the wild and crazy world of getters and setters for everything. I hated it at first, but quickly got used to it. Too used to it.

I have been spending a lot of time lately thinking more about class design. One of the things I am trying to do is avoid the trap of doing getters and setters for everything. However, much of the work I do is with entities that are mainly data containers and I am not certain that getters and setters are actually inappropriate in these cases.

Here is a simple example using public properties.

class Space {
    public String name;
    public String description;
    Space(final String name, final String description) {
        this.name = name;
        this.description = description;
    }
}

Here is a simple example using private properties and using getters and setters.

class Space {
    private String name;
    private String description;
    Space(final String name, final String description) {
        this.name = name;
        this.description = description;
    }
    public String getName() {
        return this.name;
    }
    public void setName(final String name) {
        this.name = name;
    }
    public String getDescription() {
        return this.description;
    }
    public void setDescription(final String description) {
        this.description = description;
    }
}

In these examples, both the name and the description fields should be able to be changed.

I feel like the getter/setter example is more clear and hides the implementation details of what name and description are. It would also allow for validation on set later if needed.

I have read several discussions about getters and setters being evil and/or an anti-pattern, but it really feels like those might not apply to this situation.

Maybe there are some options I have not yet considered. I'm open for suggestions!


1 Answers

The first version (public properties) is not a good idea. The second is better. As Josh Bloch would say, "favor immutability":

public class Space {
    private final String name;
    private final String description;

    public Space(final String name, final String description) {
        this.name = name;
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }
}

That being said, getters and setters tend to be overused.

like image 181
cletus Avatar answered Sep 13 '26 17:09

cletus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!