231 points · by pjmlp · 6y ago · 183 comments
I wouldn't quite phrase it that way, since it's nothing new. OCaml from the 1990s has no null value (you need to represent potentially missing values with Option). I suspect there are older examples than that.
Scala avoids the biggest pitfall of multiple inheritance elegantly, by only allowing one parent to have a constructor; classes may only be the first parent, and traits can't have constructors that take arguments. Unfortunately this doesn't mean they don't need to be initialized; in particular, vals in a mixed-in trait will be null if you try to access them in an earlier constructor.[2] As with any null, in the worst cases you may not get an error until much later on.
I'm in no way a Rust expert, but I see a lot of code with Optionals, something like
match sth {
Some(v) => do_something
None => nothing_to_do
}
This looks awfully a lot like if (something == null) {
nothing_to_do
} else {
do_something
}
It might look more pleasant, but it doesn't "solve" anything, only shifts it in a different place.Go is in the middle, because structs have no null value, only a zero value; the only thing that can be nil are pointers which I personally feel should used as little as possible.
In Rust you're passed a reference to an object. Can it be null? No, it simply can't! There does not exist a magic "null" value for references. To represent the possible absence of a value, you explicitly encode it into the type system by using `Option<T>`.
In Java you tend not to know where or when null checks have or will happen. So you tend to sprinkle null checks all over your code just incase someone somewhere forgot to check.
func getFoo() (*Foo, error)
func main(){
foo, err := getFoo()
if err != nil {
// be an adult and handle your error
}
foo.Work()
// panic because whoever implemented getFoo returned a nil object
}
Also worth noting dealing with booleans in JSON is wonky because boolean values default to false, even if that json property wasn't set over the wire. Thus you end up unmarshaling to a pointer to a boolean, which now requires nil guards throughout your codebase when working with that unmarshaled object...It means that you've told the type system what it needs to support you.
If your function tells the type system you need a reference to a type, you get a reference to that type. There's no hidden timebomb in there where you might get something that supposedly is that type but can't be treated as that type.
This lets you write your functions to accept nulls where appropriate, and require some form of unwrapping at the call site otherwise. It tells you when you've missed something and it lets you refactor without having to constantly repeat all of your checks, once you know something is valid the type system reflects that for you.
In short if you have a T in rust, you know that it's not secretly a (not)T that is implicitly allowed anywhere a T can be.
It shifts it right into your face. You're forced to do something instead of pretending that everything could be potentially null. Since the only places where you can actually encounter "null" are documented you are no longer wasting your brain cells on the happy path where you are guaranteed to never see a null value when you don't expect it. Instead you can free up all that cognitive capacity to actually write correct code that handles null values.
In the `if == null` method, the `something` reference is null, but if you have functions that also reference `something` down the line, you're going to have to check it again for null-ness.
sth.map(|v| do_something);
incidentally.Kotlin solves it much better. sth?.do_something() ?: nothing_to_do
case class Person (
firstName: String,
lastName: String,
age: Int
)
you could create an instance like this: val emily1 = Person("Emily", "Maness", 25)
and then create a new instance by updating several parameters at once, like this: // emily is married, and a year older
val emily2 = emily1.copy(lastName = "Wells", age = 26) val emily2 = emily1.newBuilder()
.lastName("Wells")
.age(26)
.build()
I think the inner Builder pattern is common enough in immutable java object implementations that they might want to include that fully in the Record class generation at some point. Most immutable object libraries that I've seen include a lot more functionality than Records, like builders. val emily2 = { ...emily1, age: 30 };
This has many advantages, one being that it provably and declaratively creates a copy, which is not the case with the builder. In fact the obsession with methods (and hence the implied state) is what makes Java a terrible misfit for functional paradigms such as immutability. // Java
val emily2 = emily1.toBuilder().age(30).build()
As far as adding the spread operator to Java, I think you'd have to require a Spreadable interface to use it or limit usage of the spread operators to records. It's not clear to me that the expressive power is worth it over a builder.Otherwise, at some point you need to add a field to Person, and then the compiler can’t tell you about all the places where your code fails to initialize the field.
Worse, some people pass builders around.
At that point, the problem of checking that you’ve passed a legal set of arguments when constructing objects is as hard as the halting problem.
You can write tests to make sure your program is typesafe, but that takes time away from writing more useful tests.
Optional arguments with reasonable defaults don't present a problem for refactoring. It does make it hard to spot the cases where the reasonable defaults don't work. One trick is to temporarily add it to the constructor, review all the errors, and then remove the constructor arg.
Kotlin has a very similar feature in its data classes, FWIW.
I really wish Java would add both default arguments for functions, and also support for passing function arguments by name.
One of these days...
Writing simple methods with few arguments helps.
Alternatively, they could automatically generate a builder class for records.
As always in java, I guess that somebody will duct tape an annotation based solution on top of the language to solve this.
F#: let updated = { old with prop = newValue }
Elixir: update = %{ old | prop: newValue }
Even JavaScript have similar stuff: const update = { ...old, prop: newValue }
just a fn in the end
The assumption of inputs based on the order of the class items frightens me!
val emily1 = Person(firstName="Emily", lastName="Maness", age=25)
Scala's approach to constructors is a good example of convention over configuration; in Java 99.9% of classes have a constructor like: this.firstName = firstName;
this.lastName = lastName;
this.age = age;
which is just ceremonial boilerplate that obscures the actual logic of what the class is doing (an IDE can generate the constructor for you, but the person maintaining your code still has to take the time to comprehend it). You can do the more complicated things in cases where you need to, but it's important to keep the simple case simple.Switch statements are standard, and Java has had them for a long time. Switch expressions are different in that the switch "statement" now returns a value that can be assigned to a variable.
it's purposefully dead simple. this is why many of us switched to alternative JVM langs ... Java can't keep up with the innovation other Langs have without breaking its philosophy of slowmoving/backwards compat
The Java 6 era of no changes whatsoever was slow as molasses. The joke back then was that even C++ got lambdas before Java.
It’s moving along a lot faster now thankfully but if it was going this fast 20 years ago we may not have needed Kotlin or Groovy
I posted a bit about it here http://www.benf.org/other/cfr/java14instanceof_pattern.html
it was first noted https://twitter.com/tagir_valeev/status/1210431331332689920 here
but the main thing is that if the 'taken' conditional is guaranteed to exit, then scope hiding happens, if not, not.
But in java
if (true) { throw new Exception(); }
is not guaranteed to exit.
So: https://github.com/leibnitz27/cfr_tests/blob/master/src_14/o...
In case you don't want to run, as of java (build 14-ea+34-1452) this prints:
Fred
WIBBLE
public class InstanceOfPatternTest10 {
static String s = "WIBBLE";
public static void test(Object obj) {
if (!(obj instanceof String s)) {
throw new IllegalStateException();
}
System.out.println(s);
}
public static void test2(Object obj) {
if (!(obj instanceof String s)) {
if(true) {
throw new IllegalStateException();
}
}
System.out.println(s);
}
public static void main(String ... args) {
test("Fred");
test2("Fred");
}
}https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.htm...
"14.21. Unreachable Statements It is a compile-time error if a statement cannot be executed because it is unreachable.
This section is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer, or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant value true, the values of expressions are not taken into account in the flow analysis."
Is there some bug or mail list thread with reaction from Java developers?
Would I ever choose it if I were in charge of a project? Probably not. But it is nice that the language is incorporating these proven features that make a huge difference. It'll make working in Java when I'm not in charge much nicer.
Does anyone know how it will play with type parameters in the interface? I know in Scala, you can simulate GADTs with that.
sealed interface Expr<A> {}
record IntExpr(Integer i) implements Expr<Integer> { }
record StringExpr(String i) implements Expr<String> { }
Will that be legal? And will switch be able to do its magic and carry that type variable through?The difference is that smartphones phones last at most 5 years, but a program that a business depends on lasts forever.
Some people just don't want to invest ANY money to improve their code. They just want to release new features. They would use Java 1 on Windows NT 4 if they could.
However, I found it's weird that hosted languages like Kotlin, Clojure or Scala are more approachable for me as they are working fine with JDK 8 like 'libraries'. They're much easier to upgrade than upgrade JDK itself.
Why is the cast even necessary? Isn't the cast only part of the type checker and thus unnecessary with a smarter type checker? For example TypeScript can do it, if you have code following an if condition that checks the type of the variable, you can use that said variable as if it were of that type without any further assertions necessary, eg.
let x: unknown;
if (typeof x === "string") {
console.log(x.charCodeAt(0));
}The backwards compatibility part:
class Foo {
void foo(Object o) { }
}
class Bar extends Foo {
void foo(Integer i) { }
}
...
Foo x = ...;
Integer i = 42;
if (x instanceof Bar) {
x.foo(i);
}
Currently this calls Foo.foo, if there was a smart cast it would call Bar.foo, possibly breaking existing code.EDIT: Added method parameter.
But don't trust me, try it!
| Welcome to JShell -- Version 11.0.5
| For an introduction type: /help intro
jshell> class Foo { void foo() { System.out.println("Super"); } }
| created class Foo
jshell> class Bar extends Foo { void foo() { System.out.println("Sub"); } }
| created class Bar
jshell> Foo f = new Bar();
f ==> Bar@58651fd0
jshell> Bar b = new Bar();
b ==> Bar@5419f379
jshell> f.foo();
Sub
jshell> b.foo();
Sub
jshell> ((Foo)b).foo();
Sub jshell> class Foo { void foo(Object o) { System.out.println("Super"); } }
| created class Foo
jshell> class Bar extends Foo { void foo(Integer i) { System.out.println("Sub"); } }
| created class Bar
jshell> Foo f = new Bar();
f ==> Bar@7f9a81e8
jshell> Integer i = 1;
i ==> 1
jshell> f.foo(i)
Super
jshell> ((Bar)f).foo(i);
Subhttps://docs.oracle.com/javase/specs/jls/se7/html/jls-15.htm...
PS: just came to my mind: that is a breaking change (in C#) due to the new operator exanple. Will never come (for C#). Maybe Java does not have this issue but most likely they have a similar problem
This is an awesome feature for typescript. Love their work there.
It might even be an intersection between an object and an interface type, and for historical reasons those have different bytecodes for invoking methods!
Flow typing is really cool, but it can make things way more complex.
For me most interesting upcoming changes are
JEP: 352: Non_Volatile Mapped Byte Buffers, JEP 345: NUMA-Aware Memory Allocation for G1 and JEP 370: Foreign-Memory Access API (Incubator). Especially FMA api [1] examples seems most promising but shipped with panama and I am not sure about the maturity yet: https://github.com/zakgof/java-native-benchmark
I wonder how GraalVM stands in this picture that beside of being polyglot, it has AOT and auto vectorization futures and I dont know if those are already/will be shipped also with openJDK
[0] https://jaxenter.com/java-14-update-news-163585.html [1] https://openjdk.java.net/jeps/370
Please nobody copy paste that class.
LocalDate is appropriate for things like user interfaces, where you're modelling an intuitive/vague concept of date-ness only meaningful in some wider human context, or where the actual time at which that day starts just doesn't matter or is unknown. For instance it may be a good type to use for annotated historical events, where the day the event happened is the most accurate you can get.
For a bank transaction where they're international by nature and usually need to be ordered temporally against each other, it's an inappropriate type. The time zone in which the date should be interpreted is important. But really for transactions you'd be better off using Instant, at least internally. Time matters too.
So it didn't quite arrive yet.
The limit as JavaVersion —> Inf = Kotlin?
I won’t complain.
List<String> names = new ArrayList<>();
names.stream().filter(String name -> "Bob Vance".equals(name)).findFirst().get();
By adding the String type declaration, a whole host of bugs in really complicated Lambdas can be eliminated and found easier when the original types and lists are being shuffled aroundEverything looks promising for me.
I completely agree as I, myself, see very few instances where I could use records in my code. But properties to remove getter/setter boilerplate? That would remove thousands of LoC. But it's not hot.
Fashion-driven development, that is.
I say this as a C# developer that would desperately want them supported in C# and was super pissed off when they were discarded from C# 8.0 (I actually need them right now, they would save me a whole day of typing today)
Do you have a source for this claim? It sounds a bit extreme, to say the least, and I had the impression OpenJDK was licensed using fairly standard terms.