0
\$\begingroup\$

I am implementing an API that implements an interface, but I do not need to implement all methods.

In that case, is it better to just return null or throw an IllegalStateException because it if not implemented?

Thanks.

@Override
public ResponseEntity get(long id) {
 // ... some meaningful code
 return response;
}
@Override
public ResponseEntity post(Request request, long id) {
 // ... some meaningful code
 return response;
// Not needed to implement this 
@Override
public ResponseEntity put(Request request, long id) {
 return null;
 // or
 throw IllegalStateException("not implemented yet")
asked Oct 21, 2022 at 9:36
\$\endgroup\$
1
  • \$\begingroup\$ This looks like a Spring rest controller, but because the context is not there it's impossible to know. This is part of the reason why the context is so important to the code review. If this is indeed a rest controller the best thing to do would be to return a 4xx status code (possibly 400 or maybe even 404). Please add some more context. I don't know why this was closed exactly but in my opinion I don't think the // some meaningful code bits are a problem because you're not asking about those methods, only the put one. \$\endgroup\$ Commented Oct 22, 2022 at 18:17

1 Answer 1

1
\$\begingroup\$

You can use UnsupportedOperationException.

Don't return null since it won't notify you about unintended use of the method and will result in a much more annoying NullPointerException instead.

answered Oct 21, 2022 at 11:34
\$\endgroup\$
1
  • 3
    \$\begingroup\$ While the title change was appropriate, the question is still off-topic due to missing code review context. \$\endgroup\$ Commented Oct 21, 2022 at 13:01

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.