Simplified code by moving if block to more defensive style