You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+62-66Lines changed: 62 additions & 66 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -11,25 +11,27 @@ Read more about TypeIDs in their [spec](https://github.com/jetpack-io/typeid).
11
11
12
12
## Installation
13
13
14
-
This library is designed to support all current LTS versions, including Java 8, whilst also making use of the features provided by the latest or upcoming Java versions. As a result, it is offered in two variants:
14
+
Starting with version `0.3.0`, `typeid-java` requires at least Java 17.
15
15
16
-
-`typeid-java`: Requires at least Java 17. Opt for this one if the Java version is not a concern
17
-
-*OR*`typeid-java-jdk8`: Supports all versions from Java 8 onwards. It handles all relevant use cases, albeit with less syntactic sugar
16
+
<details>
17
+
<summary>(Details on Java 8+ support)</summary>
18
+
Up to version 0.2.0, a separate artifact called `typeid-java-jdk8` was published, supporting Java versions 8 and higher, and covering all relevant use cases, albeit with less syntactic sugar. If you are running Java 8 through 16, you can still use `typeid-java-jdk8:0.2.0`, which is still available and remains fully functional. However, it will no longer receive updates and is limited to the TypeId spec version 0.2.0.
19
+
</details>
18
20
19
21
To install via Maven:
20
22
21
23
```xml
22
24
<dependency>
23
25
<groupId>de.fxlae</groupId>
24
-
<artifactId>typeid-java</artifactId><!-- or 'typeid-java-jdk8' -->
25
-
<version>0.2.0</version>
26
+
<artifactId>typeid-java</artifactId>
27
+
<version>0.3.0</version>
26
28
</dependency>
27
29
```
28
30
29
31
For installation via Gradle:
30
32
31
33
```kotlin
32
-
implementation("de.fxlae:typeid-java:0.2.0")// or ...typeid-java-jdk8:0.2.0
34
+
implementation("de.fxlae:typeid-java:0.3.0")
33
35
```
34
36
35
37
## Usage
@@ -38,6 +40,9 @@ implementation("de.fxlae:typeid-java:0.2.0") // or ...typeid-java-jdk8:0.2.0
38
40
39
41
### Generating new TypeIDs
40
42
43
+
44
+
#### generate
45
+
41
46
To generate a new `TypeId`, based on UUIDv7 as per specification:
42
47
43
48
```java
@@ -47,44 +52,39 @@ typeId.prefix(); // "user"
47
52
typeId.uuid(); // java.util.UUID(01890a5d-ac96-774b-bcce-b302099a8057), based on UUIDv7
48
53
```
49
54
50
-
To construct (or reconstruct) a `TypeId` from existing arguments, which can also be used as an "extension point" to plug-in custom UUID generators:
55
+
#### of
56
+
57
+
To construct (or reconstruct) a `TypeId` from existing arguments:
51
58
52
59
```java
53
-
var typeId =TypeId.of("user", UUID.randomUUID()); // a TypeId based on UUIDv4
60
+
var typeId =TypeId.of("user", someUuid);
54
61
```
62
+
As a side effect, `of` can also be used as an "extension point" to plug-in custom UUID generators.
55
63
### Parsing TypeID strings
56
64
57
65
For parsing, the library supports both an imperative programming model and a more functional style.
66
+
67
+
#### parse
58
68
The most straightforward way to parse the textual representation of a TypeID:
59
69
60
70
```java
61
71
var typeId =TypeId.parse("user_01h455vb4pex5vsknk084sn02q");
62
72
```
63
73
64
-
Invalid inputs will result in an `IllegalArgumentException`, with a message explaining the cause of the parsing failure. If you prefer working with errors modeled as return values rather than exceptions, this is also possible (and is *much* more performant for untrusted input, as no stacktrace is involved at all):
74
+
Invalid inputs will result in an `IllegalArgumentException`, with a message explaining the cause of the parsing failure.
75
+
76
+
#### parseToOptional
77
+
78
+
It's also possible to obtain an `Optional<TypeId>` in cases where the concrete error message is not relevant.
65
79
66
80
```java
67
-
var maybeTypeId =TypeId.parseToOptional("user_01h455vb4pex5vsknk084sn02q");
68
-
69
-
// or, if you are interested in possible errors, provide handlers for success and failure
70
-
var maybeTypeId =TypeId.parse("...",
71
-
Optional::of, // (1) Function<TypeId, T>, called on success
72
-
message -> { // (2) Function<String, T>, called on failure
73
-
log.warn("Parsing failed: {}", message);
74
-
returnOptional.empty();
75
-
});
81
+
var maybeTypeId =TypeId.parseToOptional("user_01h455vb4pex5vsknk084sn02q");
76
82
```
77
-
**Everything shown so far works for both artifacts, `typeid-java` as well as `typeid-java-jdk8`. The following section is about features that are only available when using `typeid-java`**.
78
83
79
-
When using `typeid-java`:
80
-
- the type `TypeId` is implemented as a Java `record`
81
-
- it has an additional method that *can* be used for parsing, `TypeId.parseToValidated`, which returns a "monadic-like" structure: `Validated<T>`, or in this particular context, `Validated<TypeId>`
84
+
#### parseToValidated
82
85
83
-
`Validated<TypeId>` can be of subtype:
84
-
-`Valid<TypeId>`: encapsulates a successfully parsed `TypeId`
85
-
- or otherwise `Invalid<TypeId>`: contains an error message
86
+
If you prefer working with errors modeled as return values rather than exceptions, this is also possible (and is *much* more performant for untrusted input with high error rates, as no stacktrace is involved):
86
87
87
-
A simplistic method to interact with `Validated` is to manually unwrap it, analogous to `java.util.Optional.get`:
88
88
89
89
```java
90
90
var validated =TypeId.parseToValidated("user_01h455vb4pex5vsknk084sn02q");
@@ -99,14 +99,27 @@ if(validated.isValid) {
99
99
```
100
100
Note: Checking `validated.isValid` is advisable for untrusted input. Similar to `Optional.get`, invoking `Validated.get` for invalid TypeIds (or `Validated.message` for valid TypeIds) will lead to a `NoSuchElementException`.
101
101
102
-
A safe alternative involves methods that can be called without risk, namely:
102
+
`Validated` and its implementations `Valid` and `Invalid` form a sealed type hierarchy. This feature becomes especially useful in more recent Java versions, beginning with Java 21, which facilitates Record Patterns (destructuring) and Pattern Matching for switch (yes, `TypeId` is a `record`):
103
+
104
+
```java
105
+
// this compiles and runs from Java 21 onwards
106
+
107
+
var report =switch(TypeId.parseToValidated("...")) {
108
+
case Valid(TypeId(var prefix, var uuid)) when "user".equals(prefix) ->"user with UUID"+ uuid;
109
+
case Valid(TypeId(var prefix, var ignored)) ->"Not a user. Prefix is "+ prefix;
110
+
case Invalid(var message) ->"Parsing failed :( ... "+ message;
111
+
};
112
+
```
113
+
Note the absent (and superfluous) default case. Exhaustiveness is checked during compilation!
114
+
115
+
Another safe alternative for working with `Validated<TypeId>` involves methods that can be called without risk, namely:
103
116
104
117
- For transformations: `map`, `flatMap`, `filter`, `orElse`
105
118
- For implementing side effects: `ifValid` and `ifInvalid`
106
119
107
120
```java
108
121
// transform
109
-
var mappedToPrefix =TypeId.parseToValidated("user_01h455vb4pex5vsknk084sn02q");
122
+
var mappedToPrefix =TypeId.parseToValidated("dog_01h455vb4pex5vsknk084sn02q")
.filter("Not a cat! :(", prefix ->!"cat".equals(prefix)); // the predicate fails
112
125
@@ -115,62 +128,46 @@ mappedToPrefix.ifValid(prefix -> log.info(prefix)) // called on success, so not
115
128
mappedToPrefix.ifInvalid(message -> log.warn(message)) // logs "Not a cat! :("
116
129
```
117
130
118
-
`Validated<T>` and its implementations `Valid<T>` and `Invalid<T>` form a sealed type hierarchy. This feature becomes especially useful in future Java versions, beginning with Java 21, which will facilitate Record Patterns (destructuring) and Pattern Matching for switch:
119
-
120
-
```java
121
-
// this compiles and runs with oracle openjdk-21-ea+30 (preview enabled)
122
131
123
-
var report =switch(TypeId.parseToValidated("...")) {
124
-
case Valid(TypeId(var prefix, var uuid)) when "user".equals(prefix) ->"user with UUID"+ uuid;
125
-
case Valid(TypeId(var prefix, _)) ->"Not a user, ignore the UUID. Prefix is "+ prefix;
126
-
case Invalid(var message) ->"Parsing failed :( ... "+ message;
127
-
}
128
-
```
129
-
Note the absent (and superfluous) default case. Exhaustiveness is checked during compilation!
130
132
131
133
## But wait, isn't this less type-safe than it could be?
132
134
<details>
133
135
<summary>Details</summary>
134
136
135
137
That's correct. The prefix of a TypeId is currently just a simple `String`. If you want to validate the prefix against a specific "type" of prefix, this subtly means you'll have to perform a string comparison.
136
138
137
-
Here's how a more type-safe variant could look, which I have implemented experimentally (currently not included in the artifact):
139
+
Here's how more type-safe variants could look like, which I have implemented experimentally (**currently not included in the artifact**):
The downside to this approach is that each possible prefix type has to be defined manually. In particular, one must ensure that the embedded prefix name is syntactically correct:
146
+
The downside to this approach is that each possible prefix has to be defined manually as its own type that contains the prefix' string representation, e.g.:
145
147
146
148
```java
147
-
staticfinalUserUSER=newUser();
148
-
record User() implements TypedPrefix {
149
+
finalclassUserimplementsTypedPrefix {
149
150
@Override
150
151
publicStringname() {
151
152
return"user";
152
153
}
153
154
}
154
-
```
155
-
156
-
This method would still be an improvement, as it allows `TypeId`s to be passed around in the code in a type-safe manner. However, the preferred solution would be to validate the names of the prefix types at compile time. This solution is somewhat more complex and might require, for instance, the use of an annotation processor.
157
-
158
-
If I find the motivation, I will complete the experimental version and integrate it as a separate variant into its own package (e.g., `..typed`), which can be used alternatively.
159
-
</details>
160
155
161
-
## A word on UUIDv7
162
-
<details>
163
-
<summary>Details</summary>
164
-
165
-
TypeIDs are purposefully based on UUIDv7, one of several new UUID versions. UUIDs of version 7 begin with the current timestamp represented in the most significant bits, enabling their generation in a monotonically increasing order. This feature presents certain advantages, such as when using indexes in a database. Indexes based on B-Trees significantly benefit from monotonically ascending values.
156
+
staticfinalUserUSER=newUser();
157
+
```
166
158
167
-
However, the [IETF specification for the new UUID versions](https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis)is a draft yet to be finalized, meaning modifications can still be introduced, including to UUIDv7. Additionally, the specification grants certain liberties in regards to the structure of a version 7 UUID. It must always commence with a timestamp (with a minimum precision of a millisecond, but potentially more if necessary), but in the least significant bits, aside from random values, it may or may not optionally include a counter and an InstanceId.
159
+
Another solution is to validate the names of the prefix types at compile time. This solution is somewhat more complex as it requires an annotation processor.
168
160
169
-
For these reasons, this library uses a robust implementation of UUIDs for Java (as its only runtime-dependency) , specifically [java-uuid-generator (JUG)](https://github.com/cowtowncoder/java-uuid-generator). It adheres closely to the specification and, for instance, utilizes `SecureRandom` for generating random numbers, as strongly recommended by the specification (see [section 6.8](https://datatracker.ietf.org/doc/html/draft-ietf-uuidrev-rfc4122bis#section-6.8) of the sepcification).
161
+
```java
162
+
@TypeId(name="UserId", prefix="user")
163
+
classMyApp {}
170
164
171
-
Nevertheless, as stated earlier, it is possible to use any other UUID generator implementation and/or UUID version by invoking `TypeId.of` instead of `TypeId.generate`.
If I find the motivation, I will complete the experimental version and integrate it as a separate variant into its own package (e.g., `..typed`), which can be used alternatively.
170
+
</details>
174
171
175
172
## Building From Source & Benchmarks
176
173
<details>
@@ -187,12 +184,11 @@ There is a small [JMH](https://github.com/openjdk/jmh) microbenchmark included:
187
184
foo@bar:~/typeid-java$ ./gradlew jmh
188
185
```
189
186
190
-
In a single-threaded run, all operations perform in the range of millions of calls per second, which should be sufficient for most use cases (used setup: Eclipse Temurin 17 OpenJDK 64-Bit Server VM, AMD 2019gen CPU @ 3.6Ghz, 16GiB memory).
187
+
In a single-threaded run, all operations perform in the range of millions of calls per second, which should be sufficient for most use cases (used setup: Eclipse Temurin 17 OpenJDK Server VM, 2021 AMD mid-range notebook CPU).
0 commit comments