exception handling

Exception Handling Is One Thing

exception handling

 

Previously we discovered why functions should do only one thing.

Today we extend this idea to exception handling. 

Exception handling is one thing.

The sole responsibility of a function can be to handle exceptions:

  public void HandleExceptionsForDoSomething()
  {
     try
     {
        DoSomething();
     }
     catch (Exception ex)
     {
        HandleException(ex);
     }
  }

Function DoSomething() does the work and HandleExceptionsForDoSomething() concentrates on handling any resulting exceptions.

HandleExceptionsForDoSomething() seems too long a name. How about TryDoSomething() since we are executing a try-catch block?

  public void TryDoSomething()
  {
     try
     {
        DoSomething();
     }
     catch (Exception ex)
     {
        HandleException(ex);
     }
  }

Much better.

Here is a real-world example from an ASP.NET WebApi project:

  [HttpPost]
  public async Task<IHttpActionResult> Register(ApiCustomerRegistration customerReg)
  {
     try
     {
        Validate(customerReg);
        var reg = customerReg.ToRegistration();
        var customer = await RegisterUseCase.Register(reg);
        return Ok(customer);
     }
     catch (Exception ex)
     {
        return HandleException(ex);
     }
  }

This Register() controller action method is a little long. It executes four lines of code and also handles exceptions. Let’s see whether we can make this method more aligned with doing ‘just one thing’. 

Let’s extract the work it does into a separate method and rename Register() to TryRegister():

  [HttpPost]
  public async Task<IHttpActionResult> TryRegister(ApiCustomerRegistration customerReg)
  {
     try
     {
        return await Register(customerReg);
     }
     catch (Exception ex)
     {
        return HandleException(ex);
     }
  }

  private async Task<IHttpActionResult> Register(ApiCustomerRegistration customerReg)
  {
     Validate(customerReg);
     var reg = customerReg.ToRegistration();
     var customer = await RegisterUseCase.Register(reg);
     return Ok(customer);
  }

I think it’s an improvement. Sure, we could have left Register() as it was – the method was far from horrible. Yet, separating the exception handling from the customer registration work makes both methods easier to read and understand.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply