Separate Objects and Separate State

Use separate objects to avoid null.

So far, we have used language features to avoid null and a possible NullReferenceException, like null checks and nullable operators and references. Let’s see how to better design our objects to avoid null when representing optional values.

Avoiding null and a possible NullReferenceException

Often, we keep all possible combinations of properties of an object in a single class.

For an e-commerce site, we create a User class with different properties: name, password, and CreditCard. But we don’t need credit card details during a trial period, for example. So we make the credit card optional by allowing it to be null. This way, we end up with a class with nullable properties and methods that only should be called when some of those properties aren’t null.

Let’s write a User class to represent either regular or premium users. We should only store credit card details for premium users to charge a monthly subscription.

Get hands-on with 1400+ tech skills courses.