How to avoid using a Triple Cast
OMG: Using a Triple Cast We've all faced situations where a seemingly simple task spirals into unexpected complexity. In 2010, I encountered such a scenario and ended up writing a triple cast! 😅 The challenge: I needed a method that would return the default value for a given type. Here's the first approach I wrote at the time: public static <T> T defaultValue(Class<T> clazz) { if (clazz == byte.class) return (T) (Byte) (byte) 0; // Other primitive types handled... return null; } Yes, this is casting madness! Let’s break it down: (byte) 0 : Initializes the default value for the byte primitive type. (Byte) : Wraps the primitive into its wrapper type, Byte . (T) : Casts it to the generic type T . While functional, this approach is overly verbose, difficult to read, and frankly, not very elegant. So, I decided to refactor it into something cleaner and more effici