Structs are occasionally useful

Some programming languages (such as C and Algol 68) formally define the idea of a struct, as a simple way of grouping together related data. Although the Java Language Specification doesn't formally define structs, the equivalent of a struct can certainly be created in Java. Here's an example of a struct which gathers together data related to books:

import java.math.BigDecimal;

/** Simple struct containing book information. */
final class Book {
  String TITLE;
  String ISBN;
  Integer NUM_PAGES;
  BigDecimal PRICE;
} 

Many dislike using such structures since they're open to abuse. Any public, mutable members are dangerous, since there's no encapsulation. This is indeed a valid objection to their wide-spread use. However, structs can still be occasionally useful, and one shouldn't be afraid to use them when appropriate. In particular, if the data is neither public nor mutable, then the usual objections to structs lose much of their force.

For example, if the above Book class was in fact a nested private class, and was just a dumb little data carrier used only inside a single class, then there would be little objection to using it:



See Also :
Immutable objects
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -