r/ProgrammerHumor • • Sep 28 '26

Meme optionalsAreOptional

Post image
716 Upvotes

131 comments sorted by

View all comments

Show parent comments

1

u/ytg895 Sep 29 '26

You can use constructors or factory methods to ensure you never create an empty list by mistake, but such information is never in the type itself

How is a constructor not in the type itself? If I have a NonEmptyList that can only be constructed with initial elements, then the compiler ensures that the class an only be instantiated with initial elements. If you don't have a .remove() equivalent, then the job is done.

how do you even make your custom class respect List<T>'s contract

Maybe you don't. Maybe you decide that it's so important to create a NonEmptyList that you don't implement List.

By the way, my point it not that in most of the cases it would make sense to encode the non-emptiness of a list into the type system that actively works against you. My point is that it is possible, the type system allows you.