DEV Community

Cover image for Refactoring 004 - Remove Unhandled Exceptions
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

Refactoring 004 - Remove Unhandled Exceptions

Creating YAGNI exception classes pollutes our environment. Let's remove them.

TL;DR: Remove unnecessary and not references empty exception classes.

Problems Addressed

  • Empty Classes

  • Namespace Polluted

Related Code Smells

Steps

  1. Check there are no references to the empty exception class.

  2. Replace the throw sentence with a generic one.

Sample Code

Before

class RangeNotSatisfiedException < StandardError
end

begin
    raise RangeNotSatisfiedException.new "Range must be betweet 0 and 10"
rescue RangeNotSatisfiedException => e
    puts e.message 
    puts e.exception_type 
end


Enter fullscreen mode Exit fullscreen mode

After

# 1. Check there are no references to the empty exception class.

# 2. Replace the throw sentence with a generic one.

begin
    raise StandardError.new "Range must be betweet 0 and 10"
rescue StandardError => exception
    puts exception.message 
    puts exception.exception_type 
end
Enter fullscreen mode Exit fullscreen mode

Type

[X] Automatic

If the Exception class has no references we can perform a Safe Remove and replace it with Exception class.

Why the code is better?

  • We remove an empty class nobody uses.

  • We shrink the code

Limitations

If we need to declare an empty exception class as documentation for an API module, our clients might need to catch it.

This is a gold plating and YAGNI example.

Tags

  • Clean up

Related Refactorings

  • Safe Remove

Credits

Image by danielkirsch from Pixabay


This article is part of the Refactoring Series.

Top comments (0)