Reduce code duplication

This is more efficient and more readable because code duplication is removed.