Using public final rather than private getters

I see most immutable POJOs written like this:

public class MyObject {
    private final String foo;
    private final int bar;

    public MyObject(String foo, int bar) {
        this.foo = foo;
        this.bar = bar;
    }

    public String getFoo() {
        return foo;
    }

    public int getBar() {
        return bar;
    }
}

Yet I tend to write them like this:

public class MyObject {
    public final String foo;
    public final int bar;

    public MyObject(String foo, int bar) {
        this.foo = foo;
        this.bar = bar;
    }
}

Note the references are final, so the Object is still immutable. It lets me write less code and allows shorter (by 5 chars: the get and ()) access.

The only disadvantage I can see is if you want to change the implementation of getFoo() down the road to do something crazy, you can’t. But realistically, this never happens because the Object is immutable; you can verify during instantiation, create immutable defensive copies during instantiation (see Guava’s ImmutableList for example), and get the foo or bar objects ready for the get call.

Are there any disadvantages I’m missing?

EDIT

I suppose another disadvantage I’m missing is serialization libraries using reflection over methods starting with get or is, but that’s a pretty terrible practice…

4

Four disadvantages that I can think of:

  1. If you want to have a read-only and mutable form of the same entity, a common pattern is to have an immutable class Entity that exposes only accessors with protected member variables, then create a MutableEntity which extends it and adds setters. Your version prevents it.
  2. The use of getters and setters adheres to the JavaBeans convention. If you want to use your class as a bean in property-based technologies, like JSTL or EL, you need to expose public getters.
  3. If you ever want to change the implementation to derive the values or look them up in the database, you’d have to refactor client code. An accessor/mutator approach allows you to only change the implementation.
  4. Least astonishment – when I see public instance variables, I immediately look for who may be mutating it and worry that I am opening pandora’s box because encapsulation is lost.
    http://en.wikipedia.org/wiki/Principle_of_least_astonishment

That said, your version is definitely more concise. If this were a specialized class that is only used within a specific package (maybe package scope is a good idea here), then I may consider this for one-offs. But I would not expose major API’s like this.

7

Get rid of the getters/setters too, and you’re fine!

This is a highly controversial topic amongst Java programmers.

Anyways, there’s two situtation where i use public variables instead (!) of getters/setters:

  1. public final To me this signals “I’m immutable” much better than just a getter. Most IDEs will indicate the final modifier with a ‘F’ during auto-completion. Unlike with getters/setters, where you have to search for the absence of a setXXX.
  2. public non-final I love this for data classes. I just expose all the fields publicly. No getters, setters, constructors. No nothing. Less than a pojo. To me this immediately signals “look, i’m dumb. i hold data, that’s all. it’s YOUR job to put the right data inside of me”. Gson/JAXB/etc. handle these classes just fine. They’re a bliss to write. There’s no doubt about their purpose or capabilities. And most importantly: You know there are no side effects when you change a variable. IMHO this results in very concise data models with few ambiguities, whereas getters and setters have this huge problem where sometimes magic happens inside of them.

5

In layman’s words:

  • You violate encapsulation in order to save a few lines of code. That
    defeats the purpose of OOD.
  • Client code will be hard coupled to the names of your class members. Coupling is bad. The whole purpose of OOD
    is preventing coupling.
  • You are also very sure your class will never need to be mutable. Things change. Change is the only thing that is constant.

20

One possible disadvantage I can see offhand is that you’re tied to the internal representation of the data in the class. This probably isn’t a huge deal, but if you use the setters, and you decide that foo and bar will be returned from some other class defined somewhere else, the classes consuming MyObject would not be required to change. You would only need to touch MyObject. However, if you use the naked values, then you would have to touch everywhere your MyObject i used.

0

If you designed a class to be immutable and then you find it needs to be mutable you have made fundamental mistakes when designing your model. I believe that here is best objects of one type are converted into another to better capture business in code. For example, UnassignedJob (has no assignee) -> AssignedJob (has assignee), instead creating a generic Job type and then mutating its assignee field. Job::setAssignee moving business logic into what’s meant to be a DTO (POJO).

Getters and setters are not APIs, POJOs should never mutate! Mutability should live along side the business rules that demand it not buried in a DTO.

Member names change and so should the getters, ergo, the argument about client code being coupled etc is thrown out of the window. IDEs help with refactoring nowadays.

As for the OOD encapsulation utopia, this is laughable at best, especially, when people start writing dumb setters which will accept anything under the sun.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật