Shouldn't auto-generated Scala methods default to UnsupportedOperationException instead of null? Follow
When I write for example a class A that extends a trait B and then use IDEA's Ctrl+Enter / "Implement Methods..." operation, the default method implementations will look like this:
def foo = null
Naturally, the IDE has no idea what I'm trying to accomplish and cannot return a sensible value. However, the intention I have as a developer when creating the method is to get a stub that either lets me quickly start implementing the method (in which case I don't care what its body is) or that lets me continue writing valid code in another class or function. In the latter case, I now have a method that will compile, will return a value, this value will potentially get passed around my program for a while and then cause a NullPointerException somewhere else. Now I have the scenario where the error (NPE) is quite far removed from the cause (a default method implementation generated by the IDE that I did not yet get around to adapting).
What one would rather have, I guess, is that invoking the method fails immediately (rather than causing an error elsewhere, potentially much later).
So for reasons of safety, it would seem preferable that IDEA by default generate the method as follows:
def foo = throw new UnsupportedOperationException
Since both 'null' and the exception may occasionally cause the compiler to complain about the type of the returned value not being what it expects, one might also expand this further (although this seems much less important) to:
def foo : Foo = throw new UnsupportedOperationException
What are your views on this? Does this make sense?
Please sign in to leave a comment.
We have general issue for generating method body by some template, like in Java editor.
As about return type, you can check "Specify return type explicitly" in "Implement methods" dialog.
Here's the issue:
OK, thanks, templates might be nice, although this would seem like a relatively low priority ("which flavor of a default implementation would you like? None of them will be useful, since you'll have to examine and fix them anyway" ;-).
Until we have templates, the question remains: should the hard-coded implementation be 'null' or an exception?
An exception appears preferable, but there may well be aspects that I have not properly considered.
It would appear that if you are too resource-constrained to do the templates then simply changing the hard-coded default might still make sense for reasons of safety.
sys.error("not implemented") might be even more idiomatic.
I agree with you that something like exception is better and when I'll add template, I'll change default to something like you suggested.
However I like Java Editor approach, which has default, which you should edit anyway:
Also I think scala.Predef will have some method like "???" or "TODO" soon, then this default will be the best one.