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:

Write code is not a simple task. It is easy to make mistakes that result in bad performance. The last...
NOTA DO ELEMAR: Este post foi escrito por Fernando Neiva de Paiva e editado por mim. Já fui cético com...
I wrote this post in 2016. Unfortunately, I lost it when I “rebooted” my blog. Anyway, I have a good...
Neste post, apresento o conceito de “Dívida Técnica” (não é débito, é dívida). Explico por que nem sempre elas são...
Uma arquitetura baseada em microsseriços exige que prestemos atenção tanto na escrita destes, quanto nos códigos que os consomem. Neste...
The example which motivated this post comes from the excellent book Designing Distributed Systems by Brendan Burns (co-founder of the...

Curso Reputação e Marketing Pessoal

Masterclasses

01

Por que sua “reputação” é importante?

02

Como você se apresenta?

03

Como você apresenta suas ideias?

04

Como usar Storytelling?

05

Você tem uma dor? Eu tenho o alívio!

Lições complementares

28

Apresentando-se do Jeito Certo

29

O mercado remunera raridade? Como evidenciar a sua?

30

O que pode estar te impedindo de ter sucesso

Recomendações de Leituras

31

Aprendendo a qualificar sua reputação do jeito certo

32

Quem é você?

33

Qual a sua “IDEIA”?

Inscrição realizada com sucesso!

No dia da masterclass você receberá um e-mail com um link para acompanhar a aula ao vivo. Até lá!

A sua subscrição foi enviada com sucesso!

Aguarde, em breve entraremos em contato com você para lhe fornecer mais informações sobre como participar da mentoria.

Crie sua conta

Preencha os dados para iniciar o seu cadastro no plano anual do Clube de Estudos:

Crie sua conta

Preencha os dados para iniciar o seu cadastro no plano mensal do Clube de Estudos:

× Precisa de ajuda?