refacted code with common funtion