Self Proxy Injection Anti-Pattern

Keywords: #Java #Spring
Because of how Spring’s implementation of AOP works (i.e. proxies), internal calls to a method in a proxied bean cannot be intercepted. This is a limitation of any AOP implementation using dynamic proxies. A way I’ve seen used to bypass this limitation is having an object with a dependency on itself, so that, for instance, internal calls to methods can also be cached when using a cache proxy1. Something like the following:

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.