Java Immutable Struct

There's something I sometimes do myself, which I've recently noticed someone else doing. That's not yet the RuleOfThree, but it's a start. Anyone else do this?

When I have a small ValueObject whose scope is not large (typically a private inner class), one that in C++ I would have perhaps used a struct for, I sometimes find it convenient to write code like this:

 class ScheduledEvent
     final Event event;
     final long time;
     ScheduledEvent(Event event, long time)
         this.event = event;    
         this.time = time;

Notice that the fields are not private, and yet they are read-only through being final. The lack of getters means that I can't secretly change the implementation. That hasn't been a problem with these trivial classes so far.

This kind of class almost always comes up when I want to make a Collection of pairs of things (e.g. Events and times above), rather than maintaining a pair of synchronized Collections. -- DavidPrice

I've been doing exactly this for the last couple of years. -- CurtisBartley

In a language with an advanced typesystem, this would be much better. For example, in CamlLanguage? you have type scheduled_event = ScheduledEvent of event * long, and in LispLanguage or even in SAC you have similar things.

I fail to see the utility of this kind of class. Whenever I see a DumbDataObject, I wonder how many places the code would be cleaner if behaviour was moved into the dumb data object, smartenin it up a bit. A similar problem occurs with enumerated types when people litter the code with conditionals based on which enumerated type they have, instead of factoring those conditionals into the enumerated type. -- JeffBay

EditText of this page (last edited July 15, 2004)
FindPage by browsing or searching

This page mirrored in JavaIdioms as of April 29, 2006