Skip to content

Instantly share code, notes, and snippets.

@khmarbaise
Created November 2, 2024 13:19
Show Gist options
  • Save khmarbaise/84a082beecc1c6331eab99899e668792 to your computer and use it in GitHub Desktop.
Save khmarbaise/84a082beecc1c6331eab99899e668792 to your computer and use it in GitHub Desktop.
Book Example / Record usage
package com.soebes.code.example.book;
public record Author(String name){
public Author {
name = NonBlankString.of(name, "author").value();
}
}
package com.soebes.code.example.book;
import java.util.Set;
import static java.util.Objects.requireNonNull;
public record Book(Title title, ISBN isbn, Set<Author> authors) {
public Book {
requireNonNull(title, "title is not allowed to be null.");
requireNonNull(isbn, "isbn is not allowed to be null.");
requireNonNull(authors, "authors is not allowed to be null.");
if (authors.isEmpty()) {
throw new IllegalArgumentException("Authors cannot be empty");
}
authors = Set.copyOf(authors);
}
}
package com.soebes.code.example.book;
public record ISBN(String isbn) {
public ISBN {
isbn = NonBlankString.of(isbn, "ISBN").value();
if (isbn.length() != 13) {
throw new IllegalArgumentException("ISBN length must be 13 characters long.");
}
}
}
package com.soebes.code.example.book;
record NonBlankString(String value, String name) {
NonBlankString {
if (name == null) {
throw new IllegalStateException("name is null");
}
if (value == null) {
throw new IllegalArgumentException("%s cannot be null".formatted(name));
}
if (value.trim().isBlank() || value.isBlank()) {
throw new IllegalArgumentException("%s cannot be blank".formatted(name));
}
}
static NonBlankString of(String value, String name) {
return new NonBlankString(value, name);
}
}
package com.soebes.code.example.book;
public record Title(String title) {
public Title {
title = NonBlankString.of(title, "title").value();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment