Techno Blender
Digitally Yours.

Why and how custom exceptions lead to cleaner, better code | by Mike Huls | Nov, 2022

0 46


Clean up your code by creating your own custom exceptions

(image by Sarah Kilian on Unsplash)

There’s a big difference between exceptions and errors; exceptions are deliberate while errors are unexpected. This article focusses on creating your own exceptiosn and how using them cleans up your code, resulting in a less error-prone program, a better flow and faster debugging. Let’s code!

To demonstrate how the custom exceptions work we’ll imagine we’re building a website. We focus on improving the log-in function of the website that currently looks like this:

(userexists, redirect and show_popup are function that are defined elsewhere in our project; what they do and how they work is irrelevant for this article)

It’s a fairly easy function:

  1. we pass an email and password
  2. check if an account exists associated with the email address. Show popup and redirect to /register page if not
  3. check if the credentials are valid. Valid: show popup. Invalid: show popup and redirect

You call the function like:

login_dirty(email='[email protected]', password='my_pa$$word')

What’s wrong with the current login function?

The problem with the login function is that it is dirty. What I mean with this is that it is responsible for things it shouldn’t be responsible for. I usually separate my project in two:

  1. clean code
  2. dirty code

To me, the difference is that clean code is unaware of your business logic. You can take ‘clean’ functions from one project and use them in a totally different one. Dirty code, however, contains business logic; for example what happens when you cannot log in. Do you get redirected? Is a popup displayed? Let’s make our login function nice and clean by removing all business logic with custom exceptions.

We want a login-function that is unburdened by any business logic. If it cannot log in a user we just have to signal that it’s not possible; some other part of our code (the dirty part) can decide what to do with it.

When you look at our function two thing can go wrong:

  1. The email address is unknown (i.e. the user is not registered)
  2. The email-password combination is incorrect

These two things are the exceptions that prevent a successful login: First we’ll write some code that allows us to raise these exceptions. Then we’ll clean up our function and the way the function is called.

Creating custom exceptions

Creating a custom exception is easier than you think:

As you see we create a new class that just inherits from the Exception class. Then, in order to have a nice message for fellow developers, we only override the __str__ method.

We can also pass arguments to our exception like in the UserNotFoundException. Here we do the exact same thing as before, only we need to store the email as an attribute using the __init__ method.

2. Cleaning up the login function

Check out how nice and clean this function looks using the new exceptions:

In addition to looking much nicer the function is more clean and pure; it is only responsible for logging in, if doesn’t have to know anything about redirecting and popups. This kind of logic should be limited to a few places in your project and shouldn’t be littered throughout. Custom exceptions help a great deal with this.

3. Calling our login

In our main.py file we can now call the login function like this:

As you see it’s really clear what happens when we cannot log in. The main benefit is that if you decide at a later time that invalid credentials should also be redirected; there are not many places to search since your business logic isn’t littered throughout your entire project.

In this article I hope to have shown why to use custom exceptions: to help keep an overview on the business logic of your code, they help to keep your functions pure/clean and debug-able. Your own exceptions are pretty easy to create and use throughout your project.

I hope everything was as clear as I hope it to be but if this is not the case please let me know what I can do to clarify further. In the meantime, check out my other articles on all kinds of programming-related topics like these:

Happy coding!

— Mike

P.S: like what I’m doing? Follow me!


Clean up your code by creating your own custom exceptions

(image by Sarah Kilian on Unsplash)

There’s a big difference between exceptions and errors; exceptions are deliberate while errors are unexpected. This article focusses on creating your own exceptiosn and how using them cleans up your code, resulting in a less error-prone program, a better flow and faster debugging. Let’s code!

To demonstrate how the custom exceptions work we’ll imagine we’re building a website. We focus on improving the log-in function of the website that currently looks like this:

(userexists, redirect and show_popup are function that are defined elsewhere in our project; what they do and how they work is irrelevant for this article)

It’s a fairly easy function:

  1. we pass an email and password
  2. check if an account exists associated with the email address. Show popup and redirect to /register page if not
  3. check if the credentials are valid. Valid: show popup. Invalid: show popup and redirect

You call the function like:

login_dirty(email='[email protected]', password='my_pa$$word')

What’s wrong with the current login function?

The problem with the login function is that it is dirty. What I mean with this is that it is responsible for things it shouldn’t be responsible for. I usually separate my project in two:

  1. clean code
  2. dirty code

To me, the difference is that clean code is unaware of your business logic. You can take ‘clean’ functions from one project and use them in a totally different one. Dirty code, however, contains business logic; for example what happens when you cannot log in. Do you get redirected? Is a popup displayed? Let’s make our login function nice and clean by removing all business logic with custom exceptions.

We want a login-function that is unburdened by any business logic. If it cannot log in a user we just have to signal that it’s not possible; some other part of our code (the dirty part) can decide what to do with it.

When you look at our function two thing can go wrong:

  1. The email address is unknown (i.e. the user is not registered)
  2. The email-password combination is incorrect

These two things are the exceptions that prevent a successful login: First we’ll write some code that allows us to raise these exceptions. Then we’ll clean up our function and the way the function is called.

Creating custom exceptions

Creating a custom exception is easier than you think:

As you see we create a new class that just inherits from the Exception class. Then, in order to have a nice message for fellow developers, we only override the __str__ method.

We can also pass arguments to our exception like in the UserNotFoundException. Here we do the exact same thing as before, only we need to store the email as an attribute using the __init__ method.

2. Cleaning up the login function

Check out how nice and clean this function looks using the new exceptions:

In addition to looking much nicer the function is more clean and pure; it is only responsible for logging in, if doesn’t have to know anything about redirecting and popups. This kind of logic should be limited to a few places in your project and shouldn’t be littered throughout. Custom exceptions help a great deal with this.

3. Calling our login

In our main.py file we can now call the login function like this:

As you see it’s really clear what happens when we cannot log in. The main benefit is that if you decide at a later time that invalid credentials should also be redirected; there are not many places to search since your business logic isn’t littered throughout your entire project.

In this article I hope to have shown why to use custom exceptions: to help keep an overview on the business logic of your code, they help to keep your functions pure/clean and debug-able. Your own exceptions are pretty easy to create and use throughout your project.

I hope everything was as clear as I hope it to be but if this is not the case please let me know what I can do to clarify further. In the meantime, check out my other articles on all kinds of programming-related topics like these:

Happy coding!

— Mike

P.S: like what I’m doing? Follow me!

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.

Leave a comment