Exceptions are too intrusive

In the previous post, I shared an example of how containers could help us to make the code clearer about what to expect as execution results.

public interface IEmployeeRepository
{
  Option<Employee> GeyById(string id);
}
 
class EmployeeRepository : IEmployeeRepository
{
  public Option<Employee> GeyById(string id)
    =>; new DbContext().Find(id);
}

But, what about exceptions?! The GetById method would throw an exception if something goes wrong (for example, if it is not possible to connect to the database), but there is nothing in the method signature about it.

The Either container

A much better approach would be:

public interface IEmployeeRepository
{
    Either<Exception, Option<Employee>> GeyById(string id);
}

class EmployeeRepository : IEmployeeRepository
{
    public Either<Exception, Option<Employee>> GeyById(string id)
    {
        try
        {
            return new DbContext().Find(id);
        }
        catch (Exception e)
        {
            return e;
        }
    }
}

The Either Type is just a regular C# struct that provides implicit conversions and very basic functional operations. It allows us to return different type results. In this example, we are using this container to make explicit that this method could result in either an employee instance or an exception.

The Try container

I love the Either container, but I don’t think it is good enough! I have been working hard to make my code even clearer.

public interface IEmployeeRepository
{
    Try<Exception, Option<Employee>> GeyById(string id);
}

class EmployeeRepository : IEmployeeRepository
{
    public Try<Exception, Option<Employee>> GeyById(string id)
        => Try.Run(return new DbContext().Find(id));
}

The Try Type, as the Either type, is just a regular C# struct that provides implicit conversions and very basic functional operations. It allows us to return different type results for failure and success, explicitly.

The most interesting thing about this approach is that the EmployeeRepository users would be forced to handle exceptions.

public IActionResult Get(string id) => _repository.GetById(id).Match<IActionResult>(
  failure: _ => DatabaseError(),
  success: e => e .Match<IActionResult>(
    some: employee => Ok(employee),
    none: () => NotFound()
  ));

Nice, right? Either and Try implementations are available on my github.

Compartilhe este insight:

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Mais insights para o seu negócio

Veja mais alguns estudos e reflexões que podem gerar alguns insights para o seu negócio:

Would you like to learn about NoSQL? Are you looking for help to make your first steps using RavenDB? So,...
Frequentemente precisamos fazer referência para outros documentos e isso é natural. Entretanto, há cenários onde o documento que queremos referenciar...
No modelo C4, o diagrama de contexto descreve, com um nível de abstração bem elevado, um sistema de software indicando...
If you ask me one tip to improve the performance of your applications, it would be: Design your objects to...
Este é o primeiro post de uma série onde pretendo compartilhar, com considerável nível de detalhe, como resolver problemas de...
Some days ago, I heard a fantastic interview with Phil Haack on the IT Career Energizer Podcast. Here is the...
Oferta de pré-venda!

Mentoria em
Arquitetura de Software

Práticas, padrões & técnicas para Arquitetura de Software, de maneira efetiva, com base em cenários reais para profissionais envolvidos no projeto e implantação de software.

× Precisa de ajuda?