Refactoring 004 - Remove Unhandled Exceptions
Creating YAGNI exception classes pollutes our environment. Let's remove them.
TL;DR: Remove unnecessary and unreferenced empty exception classes.
Problems Addressed 😔
Empty Classes
Namespace Polluted
Related Code Smells 💨
Steps 👣
Check there are no references to the empty exception class.
Replace the throw sentence with a generic one.
Sample Code 📖
Before 🚨
After 👉
Type 📝
[X] Automatic
If the Exception class has no references, you can perform a Safe Remove and replace it with Exception class.
Safety 🛡️
Unless you use metaprogramming, checking for references should be safe enough.
Why is the Code Better? ✨
You remove an empty class that nobody uses.
You shrink the code.
How Does it Improve the Bijection? 🗺️
You remove noise that breaks the 1:1 relationship between concepts and code.
Each class should represent something meaningful.
An unused exception pretends there's a case that never occurs. It lies.
By deleting it, you align your code more closely to the truth.
Now, each exception you see signals a real event, not a hypothetical one.
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.
Refactor with AI 🤖
Suggested Prompt: 1. Check there are no references to the empty exception class.2. Replace the throw sentence with a generic one.
Without Proper Instructions 📵
With Specific Instructions 👩🏫
Tags 🏷️
Clean up
Level 🔋
[X] Beginner
Related Refactorings 🔄
Credits 🙏
Image by danielkirsch on Pixabay
This article is part of the Refactoring Series
Yes, I agree with David Kelly. I like to have specific exception classes, so I can catch them and not worry about catching a real unexpected error
Developer, tech engineer, leader, founder of an AI powered app.
1moNooo, never rescue from StandardError! Please read "Exceptional Ruby" which is one of the best guides to using exceptions in Ruby.