The ideal way to deal with null pointers is to forbid them by contract if a method cannot handle them. It depends on the language how well this is supported:
- In Java, you can use the
javax.validation.constraints.NotNull annotation (or similar ones provided by IDEs like IntelliJ and Eclipse) on any method parameter that is not allowed to be null. Unfortunately, this is not very portable.
- In C#, you can use code contracts:
Contract.Requires( x != null );
- In C++, you can use references instead of pointers (but as soon as you're using smart pointers, you're out of luck)
- In Ada, you can use a
not null access type.
- Some newer languages like Rust forbid null pointers by design.
I'd generally go for the contract approach rather than checking for null at runtime if possible. It enables earlier error discovery. Usually, contract-based null checking also generates a run-time check in addition to the compiler trying to deduce whether a parameter of a method call can violate the contract at compile-time.
Arguing that you trust the caller of your library is a bad idea, because you never know if the library will be re-used in another environment. Trust in callers will always harm code reusability.