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

How does code quality fit into your CI/CD pipeline?

Continuous Integration and Continuous Deployment (CI/CD) are key for organizations wanting to deliver software at scale. CI/CD allows developers to automate...

How Stim uses Codacy to achieve high-quality code

We spoke with Tobias Sjรถsten, Head of Software Engineering at Stim, about how Codacy helps them guarantee code quality and standardization...

6 things developers should do to ship more secure code

Writing better, more secure source code is fundamental to prevent potential exploits and attacks that could undermine your software applications. However,...

Best practices for security code reviews

In today's interconnected world, where data breaches and cyber threats are increasingly common, one of your top priorities should be to...

April Product Update ๐Ÿš€

Hi there ๐Ÿ‘‹ It's been a whirlwind month, and we have big news to share: