From compact record constructors to pattern matching, from generic wildcards to chaining predicates and comparators, from jpackage to jlink - here are 11 #Java tricks handpicked from dev.java. 🧵

(Musical version of this thread: )

0/11
A #record's *canonical* constructor has one arg per component but in its *compact* form, you don't have to list them. You also don't have to (in fact, can't) assign fields, just do the checks/reassignments you need, rest happens automatically.

More: dev.java/learn/using-re…

1/11
Serialization works great with #records, no black magic needed! The guaranteed presence of constructor parameters and accessors makes serialization work with the object model and makes it easy to create reliable serializable records.

More: dev.java/learn/using-re…

2/11
The command line tool #jpackage takes a whole Java app as input and produces a fully self-contained application image that includes your code, dependencies, and a Java runtime. The cool thing: Unlike jlink, your app doesn't need to be modular!

More: dev.java/learn/jpackage/

3/11
Speaking of #jlink, you can use it to create runtime images across OS (e.g. for Windows on a Linux server):

* download/unpack JDK for target OS
* use `jlink` binary from host OS
* to its module path, add the target OS JDK's `jmods` folder

More: dev.java/learn/creating…

4/11
The #break and #continue statements can be followed by a label. You can use this to stop the execution of an outer loop (with `break`) or skip to its next iteration (with `continue`).

(Usually, other approaches are more readable, though.)

More: dev.java/learn/control-…

5/11
When #pattern #matching, you can use the introduced variables right away to make additional checks by adding `&& $boolean_expression`. This is called a guarded pattern.

More: dev.java/learn/using-pa…
More on Twitter:

6/11
While `List<Integer>` doesn't extend `List<Number>`, you can create type relationships by throwing in #generic #wildcards:

* `List<? extends Integer>` extends `List<? extends Number>`
* `List<? super Number>` extends `List<? super Integer>`

More: dev.java/learn/wildcard…

7/11
Check out the #Predicate methods:

* use `and`, `or`, or `negate` to create boolean formulas
* invert a method reference with the static factory `not`
* create an equality check with a specific object by passing it to the static `isEqual`

More: dev.java/learn/combinin…

8/11
Same for #Comparator:

* to compare objects by an attribute, use `Comparator.comparing`
* to sort by several attributes, chain comparators with `thenComparing`
* reverse with `reversed`
* use `nullsFirst` or `nullsLast` to handle `null`

More: dev.java/learn/writing-…
Write #Java #scripts (on Unix-based OS):

* create a single source file
* add shebang line `#!/path/to/bin/java --source 17`
* make file executable with `chmod +x`
* rename file and drop `.java` file extension
* run it with `./file-name` 🏃🏾

More: dev.java/learn/launchin…

10/11
Launch #JShell with predefined scripts:

* `JAVASE` imports all Java SE packages to get started right away
* `PRINTING` defines `print`, `println`, and `printf` for easier printing

E.g.: `jshell JAVASE PRINTING`

More: dev.java/learn/jshell-t…

11/11

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with Nicolai Parlog

Nicolai Parlog Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @nipafx

16 Mar
Here are 11 improvements you get when updating to #Java16 later today: from records and type patterns to `Stream`-additions and Unix domain sockets, from creating installers to more performance and observability. 🧵👇🏾

(Longer form with tons of links: nipafx.dev/java-16-guide/)
#1 Records

Express in a single line that a type is just a collection of data without need for encapsulation and let the compiler do the rest:

record Range(int low, int high) { }

That results in almost the same API as the attached class. *drops mic* Image
#2 Type Pattern Matching

This is actually two-for-one:

* first step into pattern matching
* type patterns with `instanceof`

With a type pattern you check whether a variable is of a certain type and, if so, create a new variable of that type, so you can use it without casting. Image
Read 14 tweets
14 Mar
"Towards better serialization!"

That's a guiding light of #ProjectAmber and record serialization is the first step. The Inside Java Podcast episode on that topic with Julia Boes and @chegar999 (inside.java/2021/03/08/pod…) gives great insight into how it achieves that. 🧵

1/10
First, what's wrong with regular serialization? In short:

* extralinguistic mechanism (aka "magic")
* undermines encapsulation
* causes security issues
* hinders evolving code
* holds back new Java features

In long (and why it turned out that way), see attached thread.

2/10
"The magic is where the sin was" (@BrianGoetz) and so record serialization promises "what you see is what you get", making it:

1. easy to understand
2. no magic
3. more secure
4. more performant

3/10
Read 10 tweets
12 Mar
Do you dream of "value types" in Java? So do I! Hence I was thrilled to see that Project Valhalla is slowly coming out of exploration with two draft JEPs.

Here's what they currently propose. 🧵👇🏾

(If you prefer video: https:/www.youtube.com/watch?v=WBvTilbh8S0&t=344s)

1/10
First, why value types? To bridge the divide between

* primitives (fast, no memory overhead) and
* reference types (abstraction, safety, identity)

As is, we sometimes have to choose between performance and design. And we often choose wrongly.

2/10
Draft JEP openjdk.java.net/jeps/8251554 proposes new terminology and JVM rules:

1. Interface `IdentityObject` (the boring part):

* for reference types
* called "identity classes"
* instances are "identity objects"

For identity classes / reference types everything stays as is.

3/10
Read 10 tweets
11 Feb
"When people ask me what feature do I most regret, serialization is the easy answer" - @BrianGoetz

Let's talk about serialization in Java: Why does it exist? What are the problems (even today)? Would Java have been better off without it? Can it be fixed?

1/11
NB: What follows is mostly quotes or paraphrasing from a conversation I had with Brian during my 25-hour live stream. If you want to watch the full discussion about serialization, nullability, primitives, and more, you can find it here:

2/11
Serialization was introduced because turning an object graph into bytes is valuable: You can store things on disk, in databases, or send them over the wire. But while the concept is sound, it was implemented in a horrible way.

"I wasn't on the team at the time" - Brian

3/11
Read 11 tweets
27 Jan
Project Amber is making progress on pattern matching in #JavaNext. Here are three recent developments that I'm very excited about and I think you will be as well.

(Caveats: these are ongoing discussions; none of this is final; speculation and strawman syntax ahead)
1. "Array patterns" allow matching and destructuring arrays. The `if`-line does three things:

a) is `objects` a `String` array with length 2?
b) if so, cast it to `String[]` and extract the two elements
c) declare `a` and `b` and assign the two elements to them
"Can I also bind the arrays as a whole?"

Likely. This is called an "as pattern".

"What if the array can have more elements?"

Allowing to express "at least two elements" is being considered - for example with three dots.
Read 11 tweets
10 Jun 20
Yesterday evening, we spent about two hours digging through the German #Corona app and I'm thoroughly impressed. This is a modern project, developed out there as free software (APL 2.0) on GitHub, and it has stellar documentation.

github.com/corona-warn-app

Let's have a look! 1/🧵 Simplified architecture diagram of the Corona App including the backend services.
Android and iOS apps use Google's/Apple's Exposure Notification Framework (ENF; google.com/covid19/exposu…, apple.com/covid19/contac…). Android app is written in Kotlin, iOS app in Swift. (Can't tell you much more because I'm clueless about mobile.)

2/22
Backend services:

* Java 11, Maven, Sonar, Jenkins
* Open Shift, Kubernetes, Docker
* Postgres, H2, Liquibase
* Spring Boot, Lombok, Protobuf, Guava
* JUnit 4, Hamcrest, Mockito

3/22
Read 24 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Too expensive? Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal Become our Patreon

Thank you for your support!

Follow Us on Twitter!

:(