Towards a Typesafe Map

Keywords: #Java
Say we want a heterogeneous Map in java, i.e. a map where the values have different types. Let’s further assume we know the possible keys at compile time. Barebones solution The simplest approach would be having a Map<String, Object> (or whatever other key type). We would need to remember which key corresponds to which type, and do the proper casts: String value1 = (String) map.get("someStringKey"); boolean value2 = (boolean) map.get("someBooleanKey"); /* etc.

Thoughts on static methods

Keywords: #Java
I’ve had to argue more than once why I’m making some method static, so I decided to write it down. Methods that use no instance variables should be made static. Making the method static restricts its possibilities, making it easier to reason about. It’s more restricted in the sense that it’s impossible for it to mutate any instance variable of the class where it’s defined. If it’s static: You know it doesn’t reference any state of the class where it’s defined; it can’t.

Tail recursion

When a function’s last action is calling itself, we say it’s tail recursive. For instance, a tail recursive implementation of gcd (the greatest common divisor) in Haskell is as follows: gcd :: (Integral a) => a -> a -> a gcd x y = gcd' (abs x) (abs y) where gcd' a 0 = a gcd' a b = gcd' b (a `rem` b) The interest in these functions is that they can be optimized easily by compilers, which can replace the recursive implementation by a more performant iterative one.