DEV Community

Discussion on: Unhealthy Code: Null Checks Everywhere!

Collapse
 
bendem profile image
bendem • Edited

Sometimes null is useful but generally, it plagues the code. Null being part of the type system like typescript allows is really neat (props to Kotlin, Rust and C++ too). Having the compiler yell at you for checking for null when something can never be null makes code a lot more readable without leaving the writer wondering whether this or that will actually be null or not.

Nice article.

This part though, I don't understand:

Take 2
Other languages like C#, Java, etc. won't allow you to assign a mere empty array to a collection due to rules around strong typing (i.e. []).

In those cases, you can use something like this version of the Null Object Pattern:

class EmptyArray<T> {
    static create<T>() {
        return new Array<T>()
    }
}

// Use it like this:
const myEmptyArray: string[] = EmptyArray.create<string>();

I'm not sure what this is supposed to mean. You can make empty arrays in C# and Java just fine (though you generally use an empty collection instead of raw arrays).

String[] myEmptyArray = new String[0];

// Even better
Collection<String> myEmptyCollection = List.of();
// Or in older versions
Collection<String> myEmptyCollection = Collections.emptyList();
// Or in even older versions
Collection myEmptyCollection = Collections.EMPTY_LIST;

The code you provided just does nothing, I'm not sure what problem you tried to solve by writing it.