Question

Reading effective java, it mentions that we need to validate method parameters as a good practice, throw exceptions for public and assert for private methods. But, do we need to take any measure against instance variable.

EG: (dont take example as a use case, main question is Do I need to validate instance var or Not ?. Example was used only for explaining what i mean to ask. )

class Tree {

   private Node root;

   public doSomething() {
      TreeNode node = root;
   }
}

Now lets say root was never initialized and doSomething() was called directly, it would result in NullPtrException.

Do we need to guard against it ? If yes then how ? If no then why not ?

Was it helpful?

Solution 2

The established practice to check method parameters can be generalized to check correct usage of a class. In the given example it is illegal to call method doSomething() when the instance variable root has not yet been initialized.

If you want a best practice rule, it is not to generally check instance variables, but to check that a certain usage protocol of a class is obeyed. (Unless the class is written in a way that no particular protocol needs to be followed, which is usually the better option.) This check will of course typically involve checking instance variables.

In contrast to throwing an IllegalArgumentException after a negative method parameter check, a protocol violation should lead to an IllegalStateException.

In the given example an IllegalStateException should be thrown, because that instance is not in a state where doSomething() may be called.

OTHER TIPS

How about:

if (root == null) {
    throw new SomethingException();
}
TreeNode node = root;

Simply put, just perform a null check on the root variable, and if it is null then execute code accordingly to fix that problem or throw a new exception for it.

Move any validation code of instance variables to constructors and setters so you check it whenver it will be set or changed and throw any Exceptions if input is invalid BEFORE the change is made.

this keeps the instance variables in a valid state at all times for fully constructed objects so you don't have to sprinkle extra validation everywhere else.

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