How unit testing can improve your code?

In this article I want to discuss with you about the benefits of unit testing, to give an example on why we should test the edge cases and how unit testing can improve our code.

  1. WHY unit testing?
    We already know that when doing a change in our code (even if a small one), we must test it either manually or automation.
  • Units will be performed in the early product lifecycle.
  • Units will usually protect us when we are doing a “small changes”, and it runs faster than E2E tests (We do need the E2E tests but not for each change).
  • Units will give us immediate feedback.
  • Very easy to write once you know how.
  • Units can be our “documentation” to our code and the PR will be easier to the reviewer.

2. What’s obvious to you, indistinct to others
Always keep in mind that if you have non-private methods, someone else can use them. Let’s simulate it with an example.
We have a method that gets two arguments a,b and returning the division between them, for example:

def division(a: int, b: int):
return a / b

The same developer that wrote this method knows that b can’t be a 0/None. And that’s why he is checking it in another method before calling the division method by checking if b == 0 and he is throwing an exception (ZeroDivisionError).

Yes, his functionality will work, but what will happen if another developer will use it? And won’t be aware of the edge cases?
That is the reason that I’m always suggesting to add unit tests that are checking for edge cases. In this case, if we will add a unit for division that gets b=0, the test will fail.

3. Fix the failure, improve your code
So what can we do in order to solve the problem? and how it can improve our code?

We can do two things:

  • Add the exception handler to the division method:
def division(a: int, b: int):
if b == 0:
raise ZeroDivisionError("You can't divide by 0")
return a/b

mmmm… that is ok. BUT…. maybe we can find a better solution to handle it — and not under the division method — it’s not the “division” method responsibility.

  • Create another class that inherits from int and will handle it there. For example:
class IntWithoutZero:
number: int

def __init__(self, number):
if number == 0:
raise Exception ("The number can't be a zero")
self.number = number

And now we can determine that division will get two parameters : one int and the other will be IntWithoutZero.

def division(a: int, b: IntWithoutZero):
return a / b.number

And then the responsibility for checking if the number is zero, will be on the class itself.

Units are so important , while writing them you should think about how people will use your code, you should cover the known cases and the edge, you should check for exceptions.. And by that you will improve your code.

Married to Nir and have 2 kids. With 10 years experience in writing automation — C#, java and python.