Eclipse template for unimplemented methods

Posted on by Charalampos Chrysikopoulos

This post applies to eclipse IDE.

If you have an interface (say Test) with a method declared (say testMethod) and you create a new class that implements this interface, there will be an error, that the class you declared must implement the methods defined in the interface. There is also a quick fix available that implements this methods in respect to a code template. If you choose the quick fix the result will be like:


@Override
public String testMethod() {
// TODO Auto-generated method stub
return null;
}

Say, you are working in a team (this is the default situation for a company), and you forget to implement the method. The result will be in the best case will be a null pointer exception somewhere in the code, but surely not in the method above. The return null is not the best solution for the default implementation. Even worse, the method could return an int value, then the default return value from the template would be 0, so no error is visible at runtime...

It would be better if the code would show exactly where the problem is (that means in the method testMethod) and even better, who is responsibly for this error. Both tasks are covered with the following code:


@Override
public String testMethod() {
// TODO Auto-generated method stub
throw new IllegalStateException("User X didn't do his work!");
}

This piece of code cures both problems. An exception is thrown, so everyone knows where the error is, and even better, they know who is responsible for this.

To change the template in eclipse go to eclipse preferences Java > Code Style > Code Templates
There in the tree select Code > Method body.
Press Edit... and change the pattern in


@Override
// ${todo} Auto-generated method stub
throw new IllegalStateException("${user} didn't do his work!");

Press OK and OK again and test the pattern.

This entry was posted in eclipse, template and tagged by Charalampos Chrysikopoulos