Monthly Archives: August 2014

Type Safe Heterogenous Containers in Java

As someone who has shifted from Python to Java, this article discusses two of the problems I’ve faced in Java that don’t exist in Python:

  1. Java’s type system cannot represent containers or maps with heterogenous value types. Python dicts can hold anything.
  2. Java’s methods lack named and optional parameters. These useful language features are provided by Python, Ruby, and C#.

As a response to these problems, this article presents a small library that makes them a bit less painful. We build on Effective Java’s item #29: consider typesafe heterogeneous containers. The library code is available at https://github.com/stevewedig/blog and is published to Maven for easy usage as a dependency. This is the second in a series of Java libraries I’m sharing on this blog (the first was Value Objects in Java & Python).

Article Outline

  1. Two problems with Java
  2. Get and cast: Heterogenous maps without type safety
  3. TypeMap: Effective Java’s type safe heterogenous map
  4. Symbol: A key with a value type parameter
  5. SymbolMap: An improved type safe heterogenous map
  6. SymbolBus: Heterogeneous event publishing/subscribing
  7. Using SymbolMap for named and optional parameters
  8. SymbolFormat: Parsing & writing SymbolMaps
  9. SymbolSchema: Validating the symbols in SymbolMaps

Continue reading