We use assertions to check for illegal behaviour which just shouldn't happen if everything is working as it should be, such as using NULL
as argument when it clearly shouldn't.
This is all very well when you write public functions since you can't trust that the programmer who will use them won't make a mistake. But what about private functions, which won't be accessible from the outside? Of course, the function which uses those private functions may contain a bug (i.e. you made a mistake), but should we always use assertions in private functions? Is there a line where we can say "Hey, we don't need an assertion here because due to previous assertions and usage of the private function, we can assume that the parameters are always safe"?
Now I myself am a bit skeptical about that last part - can we ever safely assume that things are always as they should be?
if (x == null) { throw new ArgumentNullException("x"); }
:), so do not overdo it.Assert
fornull
values in arguments, neither public, nor private. Instead, you should use exceptions (NullArgumentException
) or can use code contracts.