opengeospatial / geoapi

GeoAPI provides a set of interfaces in programming languages (currently Java and Python) for geospatial applications. The GeoAPI interfaces closely follow OGC specifications, adaptated to match the expectations of programmers.
http://www.geoapi.org
Apache License 2.0
118 stars 37 forks source link

Safer code list construction #91

Closed desruisseaux closed 5 months ago

desruisseaux commented 6 months ago

org.opengis.util.CodeList is a class similar to java.lang.Enum, used as the base class of all code lists. CodeList, Enum and Exception are the only types in GeoAPI that are classes instead of interfaces, because providing some kind of implementation is unavoidable for being able to define code list values.

The implementation pattern in GeoAPI 3.0 was straightforward: a CodeList has only a name, a UML identifier and an ordinal value (an integer, sometime also specified by the UML). Each code list value adds itself at construction time into a java.util.Collection provided by the implementer. The implementer (each CodeList subclass, not necessarily defined by GeoAPI) is responsible for storing the Collection, which is the actual list of codes.

The problem is in the "adds itself at construction time into a collection" sentence of above paragraph. The Java compiler was silent about this action a few years ago, but recent Java versions now produce a warning: "[this-escape] possible this escape before subclass is fully initialized". Indeed, while unlikely because of CodeList simplicity, there is a possibility that this approach allows corrupted data to leak in a system.

This issue is about modifying the way that CodeList are defined in GeoAPI for avoiding this warning. This change will have no impact on users, only on implementers who define their own CodeList. For those implementers, the java.util.Collection argument in the call to CodeList constructor will disappear, and the collection will be managed by CodeList itself.

Another change will be to reduce the use of reflection. Since Java 9 and the Java Module System, the use of reflection is restricted when the class come from a non-exported packages. These restrictions apply for example if implementers define their own code lists and do not want to make those codes publicly visible ("exported" in module-info). GeoAPI should still be able to work in those conditions. Reflections are more easy to avoid since the introduction of lambda in Java 8 (which were not available when GeoAPI 3.0 was designed), but require again a few API changes in the CodeList class. Again, it should have no impact on mosst users, but rather mostly on implementers who defines their own code lists.

desruisseaux commented 5 months ago

Done in commit dd31c1cbabcc24f782cc91964efa1f0ff336e984.