Friday, August 21, 2020

JDK16 javac xlint Warning about Default Constructors

I mentioned in my blog post "Explicit No-Arguments Constructor Versus Default Constructor" that "it is possible that one day javac will have an available lint warning to point out classes with default constructors." In that post, I referenced JDK-8071961 ("Add javac lint warning when a default constructor is created"), which has now been implemented as of JDK 16 Early Access Build #12. This post introduces that newly available javac -xlint warning.

To see this new javac -Xlint warning in action, one must download at least JDK 16 Early Access Build #12 (19 August 2020) or later.

To demonstrate the new javac -Xlint warning, we need a class with no explicit constructor so that javac will generate a "default constructor."

<rant>(By the way, a minor pet peeve of mine is when someone comments an explicit constructor with no arguments with Javadoc text that states "Default constructor." It's not really a default constructor once it's explicitly specified!)</rant>

An example of a class with no explicit constructor is available on GitHub and is shown here:

DefaultConstructor.java
package dustin.examples.jdk16;

import static java.lang.System.out;

/**
 * This class intentionally does NOT specify an explicit constructor
 * so that a "default constructor" will be generated and trigger the
 * new JDK 16 warning.
 */
public class DefaultConstructor
{
   private String name;

   public String getName()
   {
      return name;
   }

   public void setName(final String newName)
   {
      name = newName;
   }

   public static void main(final String[] arguments)
   {
      final DefaultConstructor instance = new DefaultConstructor();
      instance.setName(arguments.length > 0 ? arguments[0] : "");
      out.println("Hello " + instance.getName() + "!");
   }
}

If we compile the new class with no explicitly specified constructor with javac provided by the OpenJDK JDK 16 Early Access Build #12 or later, we won't see the new warning demonstrated unless we export the package that class is in and enable -Xlint warnings. An example of exporting the package is available on GitHub and is shown here:

module-info.java
module dustin.examples
{
   exports dustin.examples.jdk16;
}

Compiling with -Xlint

When I run javac -X with the JDK 16 Early Access Build #12 compiler, I see these Xlint-related options that are now available (emphasis added):

  -Xlint                       Enable recommended warnings
  -Xlint:(,)*
        Warnings to enable or disable, separated by comma.
        Precede a key by - to disable the specified warning.
        Supported keys are:
          all                  Enable all warnings
          auxiliaryclass       Warn about an auxiliary class that is hidden in a source file, and is used from other files.
          cast                 Warn about use of unnecessary casts.
          classfile            Warn about issues related to classfile contents.
          deprecation          Warn about use of deprecated items.
          dep-ann              Warn about items marked as deprecated in JavaDoc but not using the @Deprecated annotation.
          divzero              Warn about division by constant integer 0.
          empty                Warn about empty statement after if.
          exports              Warn about issues regarding module exports.
          fallthrough          Warn about falling through from one case of a switch statement to the next.
          finally              Warn about finally clauses that do not terminate normally.
          missing-explicit-ctor Warn about missing explicit constructors in public classes in exported packages.
          module               Warn about module system related issues.
          opens                Warn about issues regarding module opens.
          options              Warn about issues relating to use of command line options.
          overloads            Warn about issues regarding method overloads.
          overrides            Warn about issues regarding method overrides.
          path                 Warn about invalid path elements on the command line.
          processing           Warn about issues regarding annotation processing.
          rawtypes             Warn about use of raw types.
          removal              Warn about use of API that has been marked for removal.
          requires-automatic   Warn about use of automatic modules in the requires clauses.
          requires-transitive-automatic Warn about automatic modules in requires transitive.
          serial               Warn about Serializable classes that do not provide a serial version ID. 
                             Also warn about access to non-public members from a serializable element.
          static               Warn about accessing a static member using an instance.
          text-blocks          Warn about inconsistent white space characters in text block indentation.
          try                  Warn about issues relating to use of try blocks (i.e. try-with-resources).
          unchecked            Warn about unchecked operations.
          varargs              Warn about potentially unsafe vararg methods
          preview              Warn about use of preview language features
          none                 Disable all warnings

As shown in these usage details, one can use -Xlint, -Xlint:all, or -Xlint:missing-explicit-ctor to see this new warning about default constructors being exposed by classes in publicly exported packages.

Compiling the new class with -Xlint, -Xlint:all, or -Xlint:missing-explicit-ctor demonstrates the new warning about default constructors being used in a formal API:

-Xlint:all

-Xlint and -Xlint:missing-explicit-ctor

As shown in the screenshots, the warning message states (emphasis added by me): "warning: [missing-explicit-ctor] class DefaultConstructor in exported package dustin.examples.jdk16 declares no explicit constructors, thereby exposing a default constructor to clients of module dustin.examples"

The warning message that javac provides when -Xlint is appropritely specified describes the issue and specifically calls out the exported package with the offending class and the name of module that exports that package.

Summary of Steps to See Default Constructor Warning

  1. Download and "install" OpenJDK 16 Early Access Build #12 (or later) from https://jdk.java.net/16/
  2. Write Java class with no explicitly specified constructor so that javac will generate a "default constructor" (example).
  3. Export package with class with no explicit constructor via a module-info.java file (example).
  4. Compile class with no explicit constructor with -Xlint:all provided to the javac compiler.

Not All Classes with No Explicit Constructors Will Be Flagged

Not all Java classes that lack an explicit constructor will lead to this new warning being emitted even when a relevant -Xlint option is specified. As stated earlier, even the DefaultConstructor class used in this post's example does not lead to the warning message being generated until it's package is exported in the module-info.java file. Joe Darcy explains on the OpenJDK compiler-dev mailing list:

In terms of detailed criteria to issue the new warnings, there was the usual tension in warnings between reducing false positives and false negatives. For example, warning for *any* default constructor, even in a throw-away class, would be more annoying than helpful. With some guidance from the JDK code base, criteria in the current patch are a default constructor merits a warning if:

  • The class is in a named package and the packaged has an unqualified export from its module AND
  • The class is public and, if it is a nested class, all of its lexically enclosing types are public too.

An unqualified export, where the package is available to use to any module and not just named ones, was taken to indicate classes in the package can comprise a "formal API". It would be simple to change this to an unqualified export, but I wanted to avoid unwanted instances of a new warning. If a public nested class is a non-public enclosing class, the nested class is not directly part of the exported API. These combinations of kinds of exports and nesting are tested in the tests in the DefaultCtor directory.

Why Warn on Use of Default Constructors in a "Formal API" Class?

The previously mentioned Joe Darcy post explains why this warning has been added:

Some background on the design of the warning and broader usage context, while default constructors can be convenient for informal code, they can be a bit troublesome for more formal APIs, such as the public classes of packages in the JDK. One issue is that default constructors do not have javadoc. Another is that a class that semantically should not be instantiated, say it is a solely a holder for static constants and methods, can get instantiated and subclassed. (Subclasssing such a class is an anti-pattern to allow use short names for the static members, which is no longer necessary since static imports as of Java SE 5.0.)

Conclusion

This seemingly small change to add this new warning about "default constructors" in "formal API" classes has required more effort than might initially be assumed. A large number of issues were written to not only introduce the xlint warning, but to clean up numerous classes throughout the JDK that triggered this warning when compiled. Furthermore, naming and logging can often be tricky and the particular warning mssage went through review and iterative changes as well.

Friday, August 7, 2020

Project Amber Design Documents on GitHub

As discussed in a Brian Goetz post on the amber-spec-experts mailing list, an effort is currently underway for "migrating design docs to GitHub." The GitHub repository is openjdk/amber-docs and it already hosts some frequently-referenced Project Amber design documents.

The project's main README states that this repository "is for design notes, presentations, guides, FAQs, and other collateral surrounding OpenJDK Project Amber." It also explains the relationship between the Amber design documents in this repository with those hosted on the OpenJDK Project Amber site: "Most documents here are written in (pandoc) Markdown, and changes made to Markdown sources are automatically formatted and pushed to the OpenJDK website.

The Amber design documents hosted on openjdk/amber-docs are currently categorized as either design-notes or guides. Here are some of the Amber design documents already hosted in the new openjdk/amber-docs GitHub repository (mostly in GitHub-friendly MarkDown format):

The moving of OpenJDK source and artifacts to GitHub via Project Skara is paying benefits already in terms of accessibility for Java developers. The moving of Amber design documents to GitHub will likewise make these documents more readily available. As a side note, the OpenJDK design discussions and decisions are also often readily available from the relatively new Inside.java blog that features "news and views from the Java team at Oracle."

Although these Project Amber design documents have long been publicly available, this migration to GitHub should make them even easier to access and will likely increase awareness of and access to these documents. Undoubtedly, advantages inherent with a modern version control system will be gained including easier ability to make, review, track, audit, and contribute changes.

Saturday, August 1, 2020

Finalizing instanceof Pattern Matching and Records in JDK 16

Gavin Bierman has recently posted two approachable posts regarding instanceof pattern matching and records on the amber-spec-experts mailing list and both posts are thorough but succinct. I recommend that anyone interested in the latest state of these two Project Amber initiatives read these posts: "Finalizing in JDK 16 - Pattern matching for instanceof" and "Finalizing in JDK 16 - Records". Even for those not interested in the details, it is probably interesting to see the likelihood of instanceof pattern matching and records being finalized in JDK 16.

Pattern Matching instanceof Operator

In "Finalizing in JDK 16 - Pattern matching for instanceof," Bierman writes: "In JDK 16 we are planning to finalize two JEPs: Pattern matching for instanceof and Records." About instanceof pattern matching, Bierman states, "Adding conditional pattern matching to an expression form is the main technical novelty of our design of this feature."

The "Finalizing in JDK 16 - Pattern matching for instanceof" post talks about advantages of the instanceof pattern matching approach. Advantages discussed in the post include refactoring of a "common programming pattern" (checking for instanceof and then explicitly casting the thing checked with instanceof to the type it was checked against) to smaller code that is more readable. Another discussed advantage is the ability "to compactly express things with expressions that are unnecessarily complicated using statements."

Bierman also discusses scope issues, local pattern variable "poisoning", and how these will be dealt with using "flow scoping." About this, Bierman writes:

Java already uses flow analysis - both in checking the access of local variables and blank final fields, and detecting unreachable statements. We lean on this concept to introduce the new notion of flow scoping. A pattern variable is only in scope where the compiler can deduce that the pattern has matched and the variable will be bound. This analysis is flow sensitive and works in a similar way to the existing analyses. ... The motto is "a pattern variable is in scope where it has definitely matched". This is intuitive, allows for the safe reuse of pattern variables, and Java developers are already used to flow sensitive analyses.

The post on instanceof pattern matching ends with a discussion of the "Swiss cheese property" ("unfortunate interaction of flow scoping and shadowing [local pattern variables shadowing a field declaration]") and expresses the hope that IDEs will help developers to deal with these unfortunate interactions.

Records

Bierman's post "Finalizing in JDK 16 - Records" provides some nice summary descriptions related to Records. The first is, "Record classes are a special kind of class that are used primarily to define a simple aggregate of values." This is immediately followed by, "Records can be thought of as nominal tuples; their declaration commits to a description of their state and given that their representation, as well as all of the interesting protocols an object might expose -- construction, property access, equality, etc -- are derived from that state description."

This post covers the "implicit declaration of a number of members" of a Record from the Record's "state description." The post also provides a brief overview of why a developer might "explicitly [provide] a canonical constructor" and how to do so. About this, Bierman writes, "The intention of a compact constructor declaration is that only validation and/or normalization code need be given in the constructor body; the remaining initialization code is automatically supplied by the compiler."

"Finalizing in JDK 16 - Records" also discusses canonical constructor accessibility, @Override, and general annotations related to Records. The post concludes by mentioning that Records can be declared locally and explains how this is an advantage for an expected common use case of Records: "Records will often be used as containers for intermediate data within method bodies. Being able to declare these record classes locally is essential to stop proliferation of classes."

Conclusion

The two Project Amber initiatives of instanceof pattern matching and records will be welcome additions to the Java programming language. Although these features have been available in versions of the JDK before JDK 16 as preview features, it will be their finalization (hopefully in JDK 16) that will enable many more developers to apply them in production code.