refactor isValidPosition function