Avoid some null pointer and cast exceptions