Search code examples
javaverificationeffective-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.


Solution

  • If it is in the same class it is fine to trust the method.

    It is very common to do this. It is good practice to check null values in constructor's and method's arguments to make sure that nobody is passing null values into them (if it is not allowed). Then if you implement your methods in a way that they never set the "start" graph to null, don't check for nulls there.

    It is also good practice to implement unit tests for your methods and make sure that they are correctly implemented, so you can trust them.