Null Object Pattern
Empty Collections
Imagine you work for a company that writes software for dealing with legal cases.
As you are working on a feature, you discover some code:
const legalCases: LegalCase[] = await fetchCasesFromAPI(); for (const legalCase of legalCases) { if(legalCase.documents != null) { uploadDocuments(legalCase.documents); } }
Remember that we should be wary of null checks? What if some other part of the code forgot to check for a null array?
The Null Object pattern can help: you create an object that represents an empty or null
object.
Fixing It Up
Let's look at the fetchCasesFromAPI()
method. We'll apply a version of this pattern that's a very common practice in JavaScript and TypeScript when dealing with arrays:
const fetchCasesFromAPI = async function() { const legalCases: LegalCase[] = await $http.get('legal-cases/'); for (const legalCase of legalCases) { // Null Object Pattern...