f4b6a3 / uuid-creator

UUID Creator is a Java library for generating Universally Unique Identifiers.
MIT License
432 stars 44 forks source link

Code should explicitly and only throw InvalidUuidExceptions #65

Closed buko closed 2 years ago

buko commented 2 years ago

It's difficult to know which exceptions may be thrown from certain methods because method signatures do not explicitly indicate which exceptions are possible. I propose making this contract a bit more explicit by adding the appropriate throws to the method signatures:

UuidCodec#decode in particular should declare throws InvalidUuidException.

Code like NCName#decode can also fail in unexpected ways. String.charAt(0) can throw an StringIndexOutOfBoundsException. Indexing into an array with an invalid index can of course throw an ArrayIndexOutOfBoundsException. I would propose that these cases be detected beforehand and translated into an InvalidUuidException. Detecting such cases of malformed input would not, I think, impose a significant performance cost and would significantly make life easier for client developers who could be sure that no matter what String they decode they only have to handle InvalidUuidException. For example, it should be possible to write:

 try {
   codec.decode(uri.toString());
  } catch (InvalidUuidException x) {
   throw new ResourceNotFound();
 }

and be confident that any malformed URL (where the UUID has actually been encoded into a URI path segment) will appropriately return a 404 Not found.

What do you think?

fabiolimace commented 2 years ago

I like the idea.

However, in the case of unchecked exceptions, it is preferable to use the @throws tag.

fabiolimace commented 2 years ago

Now all UuidCodec implementations throw only InvalidUuidException. The runtime exception is explicit in the documentation. In addition, several validation tests were added.

fabiolimace commented 2 years ago

Released v5.0.0.

Thanks again for your suggestions!