TMDM-7456: code refactoring and fix a potenital bug