Naked Objects
By Richard Pawson and Robert Matthews

Enriching object behaviours

Accessing fields safely

In object-oriented programming it is considered good practice always to access an internal variable through its get... and set... methods. In Naked Objects this is especially important when dealing with variables that hold other business objects. The accessor and mutator methods take care of the persistence and notification issues, so accessing a variable through its get... ensures that the object is properly loaded, and changing a variable through its set... ensures that the change is made persistent and that any view of that object, whether on the user's screen or on other users' screens, is kept consistent.

The following method from the Booking class shows this practice. Each assignment is done as a set..., while each access is done using a get.... Also note that the customer field is set up using an associate... method to set the association in the Customer class as well.

public Booking actionCopyBooking() {
    Booking copiedBooking = (Booking) createInstance(Booking.class);
    copiedBooking.associateCustomer(getCustomer());
    copiedBooking.setPickUp(getPickUp());
    copiedBooking.setDropOff(getDropOff());
    copiedBooking.setPaymentMethod(getPaymentMethod());
    copiedBooking.setContactTelephone(getContactTelephone());
    return copiedBooking;
}

Value objects and internal collections don't strictly need to be accessed via their accessor methods as they already take care of the notification and persistence issues. It is, however, good practice always to use the accessor as this provides consistency in your code.