Should I throw on null parameters in private/internal methods?

前端 未结 7 1887
逝去的感伤
逝去的感伤 2021-02-05 02:56

I\'m writing a library that has several public classes and methods, as well as several private or internal classes and methods that the library itself uses.

In the publi

7条回答
  •  失恋的感觉
    2021-02-05 03:19

    This is a question of preference. But consider instead why are you checking for null or rather checking for valid input. It's probably because you want to let the consumer of your library to know when he/she is using it incorrectly.

    Let's imagine that we have implemented a class PersonList in a library. This list can only contain objects of the type Person. We have also on our PersonList implemented some operations and therefore we do not want it to contain any null values.

    Consider the two following implementations of the Add method for this list:

    Implementation 1

    public void Add(Person item)
    {
        if(_size == _items.Length)
        {
            EnsureCapacity(_size + 1);
        }
    
        _items[_size++] = item;
    }
    

    Implementation 2

    public void Add(Person item)
    {
        if(item == null)
        {
            throw new ArgumentNullException("Cannot add null to PersonList");
        }
    
        if(_size == _items.Length)
        {
            EnsureCapacity(_size + 1);
        }
    
        _items[_size++] = item;
    }
    

    Let's say we go with implementation 1

    • Null values can now be added in the list
    • All opoerations implemented on the list will have to handle theese null values
    • If we should check for and throw a exception in our operation, consumer will be notified about the exception when he/she is calling one of the operations and it will at this state be very unclear what he/she has done wrong (it just wouldn't make any sense to go for this approach).

    If we instead choose to go with implementation 2, we make sure input to our library has the quality that we require for our class to operate on it. This means we only need to handle this here and then we can forget about it while we are implementing our other operations.

    It will also become more clear for the consumer that he/she is using the library in the wrong way when he/she gets a ArgumentNullException on .Add instead of in .Sort or similair.

    To sum it up my preference is to check for valid argument when it is being supplied by the consumer and it's not being handled by the private/internal methods of the library. This basically means we have to check arguments in constructors/methods that are public and takes parameters. Our private/internal methods can only be called from our public ones and they have allready checked the input which means we are good to go!

    Using Code Contracts should also be considered when verifying input.

提交回复
热议问题