Major refactoring with generics to reduce boilerplate code