Skip to content

Latest commit

 

History

History
76 lines (58 loc) · 1.54 KB

File metadata and controls

76 lines (58 loc) · 1.54 KB

Overview

  1. Example of "idiomatic", Lombok, Jackson, Java 8-17 POJO
  2. See also, detailed explanation
  3. See also, core Java POJO examples

POJO Example

/**
 * TODO: add a BRIEF description of purpose
 * TODO: if this POJO aligns with a DB table, mention that here
 */
@Value
public class Employee {

  boolean active;

  /**
   * [16, 100]
   */
  int age;

  /**
   * [a-zA-Z-]{2,64}
   * eg. "Wil"
   */
  String name;

  @JsonProperty("firstDayOnTheJob")
  LocalDate startDate;

  @Jacksonized
  @lombok.Builder(
    builderClassName = "Builder",
    toBuilder = true)
  private Employee(
    Boolean active,  // <-- non-primitive allows you to default the value (see below)
    int age,
    String name,
    LocalDate startDate) {

    this.active = Optional.ofNullable(active).orElse(true);
    this.age = age;
    this.name = name;
    this.startDate = startDate;

    // -- Validations
    checkArgument(age <= 100, "age is too high: " + age);
    checkArgument(age >= 16, "age is too low: " + age);

    checkArgument(isNotBlank(name), "name is required");

    requireNonNull(startDate, "startDate is required and missing.");

    //TODO: other validations go here
  }
}

Usage Example

    ObjectMapper objectMapper = ...

    Employee wil = Employee.newBuilder()
      .age(35)
      .name("Wil C")
      .startDate(LocalDate.of(2020, 01, 31))
      .build();

    // NOTE: wil.active is defaulted to true

    System.out.println(
      objectMapper.writeValueAsString(wil));