fastest way to check if list doesn't contain null ?
I have a list of reference type (for example, list of string) as constructor parameter. Now i require that all of the list element must not be null. Everytime the object instance is created, the constructor will loop through the list to verify that none of the element is null. However, this have performance impact to immutable class where any modification require creating new instance of the class (because immutable class can't be modified). Is there faster way to check that list element cannot be null?
15 Replies
why not create a private internal constructor that bypasses this validation?
You already know that any existing instances of your immutable class have passed said validation.
Hmm right, maybe i can add a second public constructor with additional parameter to older instance so that if user doesn't modify the list, it will get the list from the older instance instead and avoid the check. Is this a good design ?
i honestly have no idea what you mean by "second public constructor with additional parameter to older instance"
how do users modify your immutable class?
I mean,it is immutable, the only way to modify immutable class is to create new instance of it
I am assuming you have an
Add
Remove
etc methods that internally create a new instance of your immutable and return itYes
then there is no reason to expose the new constructor to consumers
i would personally do something like
but my class have many field, it would require adding Add/Edit/Remove method for every single field wont it ?
I want user to create new instance by themselves to modify the field
^ this is the approach I would take
if you require the consumer to make all changes then you have no way of guaranteeing the data is safe / good without doing your own validation on every modification
then you'll need to run validation since the user could have included null values ¯\_(ツ)_/¯
Hmm right
Man this made me wish c# doesnt allow null by default
Anyway txn
wdym null by default?
Reference type
reference types being nullable is pretty normal, it would be weird if c# didn't allow it by default
considering you do need to make modifications to this class, is there any reason why you're making it an immutable?
Easiest way to make it thread safe. Maybe i should rethink it
well, what type of async / multithreaded access is this going to deal with?