Preventing downcasting when the object can be null and other refactoring