Chapter 18. Open to Sealed Classes

Our systems are composed of types and operations, nouns and verbs. In Java, nouns are expressed as classes and interfaces, verbs as methods; but Kotlin adds sealed class hierarchies and freestanding functions. What do they bring to the party?

Change is a constant challenge in designing software. The more people use our software, the more they think of things they want it to do. To support new use cases, we need to add new functions that work with existing data types, and new data types that work with existing functions. If our design is well aligned with the way the software has to evolve, we can add new features by adding new code and making few, localized changes to our existing code. If it isn’t well aligned, we will have to change many functions when we add a new data type, or change many data types when we need to add a function.

We feel this tension between the variability of data types and of functions most keenly in the core entities of our domain model. For example, the traveler’s itinerary is a core entity of our Travelator application. Many features of the application present views of, alter the contents of, or calculate information about itineraries. It’s no surprise then that many of the feature requests from our users affect our Itinerary type. Our travelers want to include more kinds of things in their itineraries: not just journeys and accommodation, as we saw in Chapter 10, but now restaurant bookings and attractions along ...

Get Java to Kotlin now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.