182. Listing the top three benefits of sealed classes
Maybe you have your own top three sealed class benefits that don’t match the following list. That’s OK, they are still benefits after all!
- Sealed classes sustain better design and clearly expose their intentions: Before using sealed classes, we have to rely only on the
final
keyword (which is expressive enough), and package-private classes/constructors. Obviously, package-private code requires some reading between the lines to understand its intention since it is not easy to spot a closed hierarchy modeled via this hack. On the other hand, sealed classes expose their intentions very clearly and expressively. - The compiler can rely on sealed classes to perform finer checks on our behalf: Nobody can sneak a class into a hierarchy closed via sealed classes. Any such attempt is rejected via a clear and meaningful message. The compiler is guarding for us and acts as the first line of defense against any...