Skip to Content
97 Things Every Java Programmer Should Know
book

97 Things Every Java Programmer Should Know

by Kevlin Henney, Trisha Gee
May 2020
Beginner
267 pages
7h 37m
English
O'Reilly Media, Inc.
Content preview from 97 Things Every Java Programmer Should Know

Chapter 73. Simple Value Objects

Steve Freeman

Classes that represent Value Objects don’t need getters or setters. Java developers are usually taught to use getters for accessing fields, like this:

public class Coordinate {
    private Latitude latitude;
    private Longitude longitude;

    public Coordinate(Latitude latitude, Longitude longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
    }

    /**
     * @return the latitude of the Coordinate
     */
    public Latitude getLatitude() {
        return latitude;
    }

     /**
      * @return the longitude of the Coordinate
      */
    public Longitude getLongitude() {
        return longitude;
    }
}

System.out.println(thing.getLatitude());

The idea is that getters encapsulate how values are represented in an object, providing a consistent approach across a codebase. It also allows for protection against aliasing, for example, by cloning collections before returning them.

The style has its origins in the early days of JavaBeans, when there was a lot of interest in graphical tooling using reflection. There might also have been some influence from Smalltalk (the classic object-oriented language), in which all fields are private unless exposed via an accessor; read-only fields have getters, but no setters.

In practice, not all classes play the same role and, lacking an alternative structure in the language, many coders write Java classes that are actually Value Objects: a simple set of ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

97 Things Every Programmer Should Know

97 Things Every Programmer Should Know

Kevlin Henney
Java Coding Problems

Java Coding Problems

Anghel Leonard
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781491952689Errata Page