Compact Canonical Record Constructor – Object-Oriented Programming

Compact Canonical Record Constructor

The compact canonical record constructor is a more concise form of the normal canonical record constructor. It eliminates the need for a parameter list and the initialization of the component fields. The parameter list is derived from the component list declared in the record header, and the initialization of all component fields is left to the implicit canonical record constructor. In fact, the component fields cannot be accessed in the compact constructor, as the component names refer to the parameter names of the implicit canonical constructor. Note that the implicit canonical record constructor is generated when the compact constructor is provided in the record class declaration. The compact constructor is called in a new expression, exactly as any other constructor, passing the argument values in the call.

In Example 5.30, the compact canonical constructor for the record class CD is implemented at (2). It has no parameter list and it does not initialize the component fields. It only sanitizes the values passed to the constructor. Again running the DataUser class in Example 5.28 with the record class CD in Example 5.30 produces the same results.

The implicit canonical record constructor is called before exiting from the compact canonical constructor; therefore, a return statement is not allowed in the compact constructor. The compact constructor primarily functions as a validator for the data values before they are assigned to the component fields by the implicit canonical record constructor.

Previous restrictions mentioned for the normal canonical record constructor also apply to the compact canonical record constructor.

Example 5.30 Compact Record Constructor and Non-Canonical Constructor

Click here to view code image

package record.constructors.compact;
import java.time.Year;
/** A record class that represents a CD. */
public record CD(String artist, String title, int noOfTracks,             // (1)
                 Year year, Genre genre) {
  // Compact canonical record constructor                                    (2)
  public CD {
    // Sanitize the values passed to the constructor:                        (3)
    artist = artist.strip();
    title = title.strip();
    noOfTracks = noOfTracks < 0 ? 0 : noOfTracks;
    year =  year.compareTo(Year.of(2022)) > 0? Year.of(2022) : year;
    genre = genre == null ? Genre.OTHER : genre;
    // Cannot explicitly assign to component fields:                         (4)
    // this.artist = artist;                    // Compile-time error!
  }
  // A non-canonical record constructor                                      (5)
  public CD() {
    this(” Anonymous  “, ”  No title  “, 0, Year.of(2022), Genre.OTHER);  // (6)
  }
}


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *