Pattern 9 - Design for changes

As with building any API, you have to keep your users in mind when you'll eventually plan to change it. Thus, you'll have to keep possible future changes in mind when you design it! The exported packages in your module are the public API, so your users could be accessing any of them. This means that changing any types in the exported packages of your module will need to be approached with caution, as it could potentially break any consumers of your module.

Of course, this depends on the change itself. If you are adding a new type to an exported package, or are adding new member variables or methods to existing exported types, the changes are still backward compatible. But if you want to remove member variables from exported types or change method signatures, you end up breaking code that uses those APIs.

Here are some guidelines that help minimize possible changes to module APIs:

  • Keep the exported types as lightweight as possible. We've already seen how you can expose interface types that are backed by encapsulated implementation types. Having lesser moving parts in exposed types makes them less likely to change in future.
  • When you plan to make backward incompatible changes, plan to give your module consumers a heads up. This could be in the form of the @Deprecated annotation on the methods that you plan to remove, for example. If possible, try to provide both the old and new APIs together (with clear deprecation notices on the old APIs) so that the consumers of your module have enough time to switch their code to use your new APIs.

The  @Deprecated annotation in Java 9 can be used on a module declaration too! This is very handy when you want to mark a complete module for deprecation. Here's an example:

    @Deprecated(since = "9", forRemoval = true)
module mymodule { }

This marks the module as deprecated from Java 9 onward, and also that it could be a removed in any future release. If any module tries to use your module with a  requires, the compiler will issue a warning about the deprecation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.134.17