Sometimes I see programmers that use "assert", and other times I see null checking for parameters and throws Exception.
What's the best option?
Sometimes I see programmers that use "assert", and other times I see null checking for parameters and throws Exception.
What's the best option?
Take always into account that an "assert" is not always enabled. This is the main rule you should have always in your mind. Think of it as a mechanism to detect bugs in your code, unexpected situations that should not happen (pre/postconditions). On the other hand, throw an exception (i.e. IllegalArgumentException) if there is a chance to get that null value from the caller.
For example:
It depends on your usage,
If you want your parameters not null explicitly then you should assert or throw IllegalArgusmentException
On the other way if its ok if it is null
then simple check for not null and assign with fallback value and move ahead the code
I don't know where I read that, (maybe someone will point out), but the general rule is like that:
1) for interfaces Use null checks, because interfaces must handle all parameters, including null, but that doesn't prohibit you from additionally throwing an exception.
2) throw exception in exceptional situations, like in your private method that shouldn't take null as an argument.
3) use assert but don't rely on it too much because it can be disabled, and not included in resulting byte code. So use it while development, but not for real environment.