DEV Community

Bertil Muth
Bertil Muth

Posted on

Getter naming conventions

In Java and similar languages that don't have a built-in property concept, it is common to make fields private and accessible to the object's outside only through getter methods.
The Java Beans naming convention suggests to use the name getX() for the getter method of a field x (most of the time) , like so:

public class User{
    private Name name;

    public Name getName(){
        return name;
    }
    ...
}
Enter fullscreen mode Exit fullscreen mode

I didn't question it when I started programming. Then I heard of several people, like Martin Fowler, who didn't care about that convention. They write name() for the example getter instead.

Looks a lot better, so I started adopting it. Then I ran into problems with libraries that expect the Beans convention.
Another benefit of classes adhering to the Beans convention: in an IDE, you can easily find out all the properties of a library's class if you just type in the first three letters: get.

So, if you use getter methods, which naming convention do you use?

Top comments (4)

Collapse
 
fpuffer profile image
Frank Puffer • Edited

My recommendation: Avoid getters and especially setters whenever possible. Try to make classes immutable and assign all attributes in the constructors.

Then I ran into problems with libraries that expect the Beans convention.

Yes, unfortunately.

Another benefit of classes adhering to the Beans convention: in an IDE, you can easily find out all the properties of a library's class if you just type in the first three letters: get.

So you want to understand the internals of the class. In a well-designed library this should not be neccessary.

By the way, one of the reasons why I have to work this weekend are classes with plenty of getters and setters which I need to modify.

Collapse
 
bertilmuth profile image
Bertil Muth • Edited

BTW, having no setters and passing in the fields‘ values in the constructor alone doesn’t make your objects immutable. And if you e.g. want to implement value objects in Java, that are immutable, you need getters.

Collapse
 
bertilmuth profile image
Bertil Muth

As always, it depends. In general, I do try to avoid it, but there are definitely valid cases for it (e.g. parameter objects).

UI libraries for example carry a lot of state on their objects.

Sorry to hear you have to work on weekends.

Collapse
 
jordan33h profile image
Jordan

Bean/Model I recommend stick to get set and constructor if lesser field, it is pretty confusing with functional method.

Simply apply Lombok @Data or @Getter @Setter with chain, maintain readable code.