use raii to remove code duplication