Should exception check be explicitly done in public function if private function needs the same input

StackOverflow https://stackoverflow.com/questions/20278002

  •  06-08-2022
  •  | 
  •  

Question

The effective java makes it clear that an assert be used to verify parameters of a private function. If a method is a public method then the method should throw a NPE if a null is an invalid parameter.

Eg:

public void foo (Sting str) {
   char[] ch = str.toCharArray();
}

In the code above, we dont need an explicit check to ensure str is null, or not as null.toCharArray wil l throw the NPE

But what if the code changes to something like this:

   public void foo (String str) {
      List<String> strList = new ArrayList<String>();
      bar (str, strList);
   }

   private void bar(String str, strList) {
        assert strList != null;
        char[] ch = str.toCharArray();
        ... ... .. 
   }

In such a code it falls on private function bar to throw a NPE. According to effective java a private code should only verify via an assert. Will the following code be considered a better practice than code above ?

 public void foo (String str) {
          if (str == null)  throw NPE;
          List<String> strList = new ArrayList<String>();
          bar (str, strList);
       }

       private void bar(String str, strList) {
            assert str != null;
            assert strList != null;
            char[] ch = str.toCharArray();
            ... ... .. 
       }
Was it helpful?

Solution

In your public method foo, you have the following

if (str == null) throw new NullPointerException;

This is often called guard clauses and is generally more readable than just letting a null pointer exception be thrown by not including anything.

Regarding assert, it generally as @Sotirios mentions is not used in production code. Check out this answer for additional information: Java assertions underused.

There is definitely some subjectivity here which is better, but from a readability viewpoint, the guard clause in the public method appears to more readable. The assert provides no additional value especially if that private method is only called from that one public method. The assert would never trigger.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top