I think what you are looking for are method preconditions or, more generally, contracts.
Let's assume your code is split up into many small methods, as it should be. Then you define preconditions and postconditions for every method. These need to be met, otherwise failure is to be expected. If you do this consistently, the question of where to put these checks will pretty much answer itself in quite an intuitive way.
As an example, let's consider two ways you could write a method that does something with a User
:
private void doSomethingWithUser(User u) {
if (u == null) {
/* take appropriate steps */
}
/* perform some action on the user object */
}
Above, the method takes care of the null-check. Hence, there is no need for the calling code to do it.
/*
* Does this and that with the User.
* Precondition: the User `u` may not be null!
*/
private void doSomethingWithUser(User u) {
/* perform some action on the user object */
}
Here, the method does not check u
for null
, but reading the comment, we can see that this is how the method was designed. It is the responsibility of the calling code to hand in a non-null object, else the behavior will be undefined.
Of course, now you face the decision of when to go with which of these. And obviously, you can set preconditions for your methods and have them still perform appropriate checks. They could then return a value that indicates an error or throw an Exception, as is pretty common.
EDIT:
but if there are lots of objects need to check before I use them?should I check them all?
Consider this:
public class SimpleClass {
public static void main (String[] args) {
User sware = new User("sware");
User domdom = new User("domdom");
doSomethingWithUser(sware);
doSomethingWithUser(domdom);
}
}
Here, we are declaring and initializing two objects in the main
method. We know they are not null. We then use them right away. No matter if that method checks for null
or not, I would not perform such a check outside - there is just no way those objects would be null
.
Now, imagine we have a much more complex code:
public class VeryComplexClass extends ComplexClass implements ComplexInterface {
/* ... */
@Override
private boolean doSomethingWithUser(User u) {
if (u == null) {
return false;
}
/* ... */
}
}
Let's say we need to implement the doSomethingWithUser()
method to satisfy the interface. Or the method comes from the parent class and we override it. We don't know where u
will be coming from. Who could potentially call this method? A user from the outside of the class? Or is this method being used by the class itself? Will it be called with a member being passed in? It is pretty hard to tell at this point. Hence, I would recommend to put a null
check into place.