check function exists before running it
code refactor and optimzation