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


i'm writing library has several public classes , methods, several private or internal classes , methods library uses.

in public methods have null check , throw this:

public int dosomething(int number) {     if (number == null)     {         throw new argumentnullexception(nameof(number));     } } 

but got me thinking, level should adding parameter null checks methods? start adding them private methods? should public methods?

ultimately, there isn't uniform consensus on this. instead of giving yes or no answer, i'll try list considerations making decision:

  • null checks bloat code. if procedures concise, null guards @ beginning of them may form significant part of overall size of procedure, without expressing purpose or behaviour of procedure.

  • null checks expressively state precondition. if method going fail when 1 of values null, having null check @ top way demonstrate casual reader without them having hunt it's dereferenced. improve this, people use helper methods names guard.againstnull, instead of having write check each time.

  • checks in private methods untestable. introducing branch in code have no way of traversing, make impossible test method. conflicts point of view tests document behaviour of class, , that class's code exists provide behaviour.

  • the severity of letting null through depends on situation. often, if null does method, it'll dereferenced few lines later , you'll nullreferenceexception. isn't less clear throwing argumentnullexception. on other hand, if reference passed around quite bit before being dereferenced, or if throwing nre leave things in messy state, throwing more important.

  • some libraries, .net's code contracts, allow degree of static analysis, can add benefit checks.

  • if you're working on project others, there may existing team or project standards covering this.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -