Preventing downcasting when the object can be null and other refactoring
fixing the incorrect display of line item count