[java] How much should a function trust another function

Consider the following two functions in a class called Graph. The entire source code is found here: http://www.keithschwarz.com/interesting/code/?dir=dijkstra.

public void addNode(T node) {         mGraph.put(node, new HashMap<T, Double>());     }  public void addEdge(T start, T dest, double length) {         mGraph.get(start).put(dest, length);     } 

Here, the addEdge method is blindly trusting addNode method that it has added hashmap to mGraph. Is it a common practice to trust that other methods in class are doing their job correctly ? Or is it recommended that a method be skeptical of everything and do a check something like:

 public void addEdge(T start, T dest, double length) {             Map m = mGraph.get(start)             if ( m ! = null)  ... ...          } 

Once again, I am interested in knowing whats commonly done and whats ideally recommended.

This question is related to java verification effective-java

The answer is


Typically this is bad practice. Since it is possible to call addEdge before addNode and have a NullPointerException (NPE) thrown, addEdge should check if the result is null and throw a more descriptive Exception. In my opinion, the only time it is acceptable not to check for nulls is when you expect the result to never be null, in which case, an NPE is plenty descriptive.


The addEdge is trusting more than the correction of the addNode method. It's also trusting that the addNode method has been invoked by other method. I'd recommend to include check if m is not null.


That's where constructors come into play. If you have a default constructor (eg. with no parameters) that always creates a new Map, then you're sure that every instance of this class will always have an already instantiated Map.


My 2 cents.

This is a loaded question imho. A rule of thumb I use to is see how this function will be called. If the caller is something I have control over then , its ok to assume that it will be called with the right parameters and with proper initialization.

On the other hand if its some client I don't control then it is a good idea to do thorough error checking.


Such debugging is part of the development process and should not be the issue at runtime.

Methods don't trust other methods. They all trust you. That is the process of developing. Fix all bugs. Then methods don't have to "trust". There should be no doubt.

So, write it as it should be. Do not make methods check wether other methods are working correctly. That should be tested by the developer when they wrote that function. If you suspect a method to be not doing what you want, debug it.