replace: refactor checking ref validity