Home Developer Coding Problems: One Less Exception

Coding Problems: One Less Exception

Author

Date

Category

java.util.NoSuchElementException: No value found for ‘USD’
at scala.Enumeration.withName(Enumeration.scala:124)

Dammit! I hate it when code blows in production.
For some cases there’s just no tests or static analysis that can cover you.

This is one of those cases. Calling the withName method with an inexistent value in an Enumeration will blow up. Sure, it throws an Exception, but since Scala has unchecked exceptions, the compiler won’t warn you.

https://gist.github.com/mrfyda/ad94180cd00613cf314b

Unfortunately, it wasn’t the first time we had exactly this problem, so we agreed to start avoiding the withName method and writing it as:

https://gist.github.com/mrfyda/d9241e947c1600866069

Since find returns an Option, the code needs to be ready to deal with the possibility of a non existing value.

We also want all of our users to stay safe, so today we’re adding a new code pattern: Prohibit withName on Enumeration.
You can check your code for this issue and fix it before it blows in production!


Edit: We just published an ebook: “The Ultimate Guide to Code Review” based on a survey of 680+ developers. Enjoy!


About Codacy

Codacy is used by thousands of developers to analyze billions of lines of code every day!

Getting started is easy – and free! Just use your  GitHub, Bitbucket or Google account to sign up.

GET STARTED

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subscribe to our newsletter

To be updated with all the latest news, offers and special announcements.

Recent posts

Code reviews in large-scale projects: best practices for managers

Managing code reviews for large-scale projects can be challenging, as the volume and complexity of the code might seem overwhelming. However,...

Now live: introducing Coverage summary on your Git provider!

You spoke; we listened! We’re very excited to announce you can now see the Coverage summary directly on GitHub as a...

Top mistakes your dev team makes when performing code reviews

Code reviews are an essential part of any software development process and are crucial for improving code quality. However, despite their...

Codacy Pulse now supports Bitbucket integration

We're very excited to announce that Codacy Pulse now supports Bitbucket integration! You can collect changes and deployment data from Bitbucket...

Tips for implementing DORA metrics and how Pulse can help

DORA (DevOps Research and Assessment) metrics are a powerful way to measure the performance of software delivery organizations. By tracking key...