Refactoring 004 - Remove Unhandled Exceptions

Refactoring 004 - Remove Unhandled Exceptions

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

Maxi Contieri
·Feb 10, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Problems Addressed
  • Related Code Smells
  • Steps
  • Sample Code
  • Type
  • Why the code is better?
  • Limitations
  • Tags
  • Related Refactorings
  • Credits

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

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

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.

 
Share this

Impressum

Technical Opinions are my own. I don't have the revealed truth.

Software Design is a creative activity. These are hints and not rigid rules.

I write on BackEnd Business Systems and OOP Design. My advice/experience might not suit other systems.

You can write me at info(at)maximilianocontieri.com