refactored a little piece of code using templates