Record construction
Stephen Colebourne
scolebourne at joda.org
Wed Mar 14 21:52:11 UTC 2018
On 14 March 2018 at 14:55, Brian Goetz <brian.goetz at oracle.com> wrote:
> The constructor syntax
>
> record Point(int x, int y) {
> Point {
> }
> }
>
> is proposed as a shorthand for an explicit default constructor:
Minor tweak, but class names can get quite long. A keyword would be preferable:
record Point(int x, int y) {
new {
Preconditions.require(x > 0);
}
}
It also does not clash with existing constructors if a way were found
to add `new{}` to non-record classes.
> This makes both validation and normalization work; if the constructor body
> contains only:
>
> Preconditions.require(x > 0);
This example skips some boilerplate, so is a little misleading. The
correct invocation (using our library) would be one of these:
ArgChecker.isTrue(x > 0, "x must be positive");
ArgChecker.isPositive(x, "x");
This repetition is one reason why `requires x > 0` has appeal (as it
can infer the variable name).
While not entirely off the fence, I'm coming down on the side that
says it is better to allow any preconditions library, rather than just
make it a language feature.
Wild idea - is there a way for the library method to obtain the
variable name and type used at the call site?:
public static void isTrue(CallsiteBooleanExpression expr) {
if (expr.isFalse()) {
throw new IllegalArgumentExpression(expr.expressionString() + "
must be true");
}
}
Stephen
More information about the amber-dev
mailing list