Created
November 2, 2024 13:19
-
-
Save khmarbaise/84a082beecc1c6331eab99899e668792 to your computer and use it in GitHub Desktop.
Book Example / Record usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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."); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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