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():
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.
Exception Handling Is One Thing
/by Olaf ThielkeException Handling Is One Thing
Yesterday 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:
Function
DoSomething()
does the work andHandleExceptionsForDoSomething()
concentrates on handling any resulting exceptions.HandleExceptionsForDoSomething()
seems too long a name. How aboutTryDoSomething()
since we are executing atry-catch
block?Much better.
Here is a real-world example from an ASP.NET WebApi project:
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()
toTryRegister()
: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.